diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4c1fe39918..102a7302f2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -206,7 +206,7 @@ jobs:
name: Prepare mysql directory
run: sudo chown -R $USER /usr/local
- - if: matrix.ruby-version == '2.4.10'
+ - if: matrix.ruby-version == '2.4.10'
name: Cache mysql55
id: mysql55-cache
uses: actions/cache@v3.2.2
@@ -265,6 +265,16 @@ jobs:
path: lib/coverage_*/.resultset.json
retention-days: 2
+ - name: Generate gem manifest
+ run: rake test:multiverse:gem_manifest
+
+ - name: Save gem manifest
+ uses: actions/upload-artifact@v3
+ with:
+ name: gem_manifest_${{ matrix.ruby-version }}.json
+ path: gem_manifest_${{ matrix.ruby-version }}.json
+ retention-days: 2
+
infinite_tracing:
needs: run_rubocop
@@ -336,4 +346,4 @@ jobs:
token: ${{ secrets.GITHUB_TOKEN }}
resultPath: lib/coverage_results/.last_run.json
failedThreshold: 93
- failedThresholdBranch: 84
+ failedThresholdBranch: 85
diff --git a/.github/workflows/ci_cron.yml b/.github/workflows/ci_cron.yml
index c124554c09..8f8d5f6aab 100644
--- a/.github/workflows/ci_cron.yml
+++ b/.github/workflows/ci_cron.yml
@@ -54,7 +54,6 @@ jobs:
with:
ruby-version: ${{ matrix.ruby-version }}
- # ,railsedge goes in 2.7+
- name: Set up mini-envs for ruby version
uses: kanga333/variable-mapper@master
with:
@@ -71,16 +70,16 @@ jobs:
"rails": "norails,rails61,rails60,rails52,rails51,rails42"
},
"2.7.7": {
- "rails": "norails,rails61,rails60,rails70"
+ "rails": "norails,rails61,rails60,rails70,railsedge"
},
"3.0.5": {
- "rails": "norails,rails61,rails60,rails70"
+ "rails": "norails,rails61,rails60,rails70,railsedge"
},
"3.1.3": {
- "rails": "norails,rails61,rails70"
+ "rails": "norails,rails61,rails70,railsedge"
},
"3.2.1": {
- "rails": "norails,rails61,rails70"
+ "rails": "norails,rails61,rails70,railsedge"
}
}
diff --git a/.github/workflows/ci_jruby.yml b/.github/workflows/ci_jruby.yml
index 13a60f0c04..105246d7bf 100644
--- a/.github/workflows/ci_jruby.yml
+++ b/.github/workflows/ci_jruby.yml
@@ -23,16 +23,10 @@ jobs:
run: 'git config --global init.defaultBranch main'
- uses: actions/checkout@v3
- # - curl is needed for Curb
- # - xslt is needed for older Nokogiris, RUBY_VERSION < 2.5
- # - sasl is needed for memcached
- - name: Install OS packages
- run: sudo apt-get update; sudo apt-get install -y --no-install-recommends libcurl4-nss-dev libsasl2-dev
-
- - name: Install Ruby jruby-9.3.9.0
+ - name: Install Ruby jruby-9.4.2.0
uses: ruby/setup-ruby@v1
with:
- ruby-version: jruby-9.3.9.0
+ ruby-version: jruby-9.4.2.0
- name: Bundle
run: bundle install
@@ -122,12 +116,6 @@ jobs:
matrix:
multiverse: [agent, background, background_2, database, frameworks, httpclients, httpclients_2, rails, rest]
steps:
- - name: Set the default Java version
- run: sudo update-alternatives --set java ${JAVA_HOME_8_X64}/bin/java &&
- sudo update-alternatives --set javac ${JAVA_HOME_8_X64}/bin/javac &&
- java -version &&
- javac -version
-
- name: Configure git
run: 'git config --global init.defaultBranch main'
@@ -137,14 +125,10 @@ jobs:
- name: Install JRuby
uses: ruby/setup-ruby@v1
with:
- ruby-version: jruby-9.3.9.0
- env:
- JAVA_HOME: /usr/lib/jvm/temurin-8-jdk-amd64
+ ruby-version: jruby-9.4.2.0
- name: Bundle
run: bundle install
- env:
- JAVA_HOME: /usr/lib/jvm/temurin-8-jdk-amd64
- name: Run Multiverse Tests
run: ./.github/workflows/scripts/retry_command
@@ -155,7 +139,6 @@ jobs:
SERIALIZE: 1
DB_PORT: ${{ job.services.mysql.ports[3306] }}
JRUBY_OPTS: --dev --debug
- JAVA_HOME: /usr/lib/jvm/temurin-8-jdk-amd64
- name: Annotate errors
if: ${{ failure() }}
diff --git a/.github/workflows/scripts/generate_release_notes.rb b/.github/workflows/scripts/generate_release_notes.rb
new file mode 100644
index 0000000000..777fc421ab
--- /dev/null
+++ b/.github/workflows/scripts/generate_release_notes.rb
@@ -0,0 +1,67 @@
+#!/usr/bin/ruby
+# This file is distributed under New Relic's license terms.
+# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
+# frozen_string_literal: true
+
+require 'date'
+require_relative '../../../lib/new_relic/version'
+
+class GenerateReleaseNotes
+ DIVIDER = '---'
+ SUPPORT_STATEMENT = <<~SUPPORT_STATEMENT
+
+ We recommend updating to the latest agent version as soon as it's available. If you can't upgrade to the latest version, update your agents to a version at most 90 days old. Read more about [keeping agents up to date](/docs/new-relic-solutions/new-relic-one/install-configure/update-new-relic-agent/).
+
+ See the New Relic Ruby agent [EOL policy](https://docs.newrelic.com/docs/apm/agents/ruby-agent/getting-started/ruby-agent-eol-policy/) for information about agent releases and support dates.
+
+ SUPPORT_STATEMENT
+
+ def build_metadata
+ changelog = File.read('CHANGELOG.md')
+ latest_entry = changelog.split('##')[1].prepend('##')
+ titles = latest_entry.scan(/^- \*{2}(.*?)\*{2}$/).flatten # Match strings between sets of '**'
+ metadata = Hash.new { |h, k| h[k] = [] }
+
+ titles.each do |t|
+ category = t.split(':').first
+ case category
+ when 'Feature'
+ metadata[:features] << t.delete_prefix('Feature: ')
+ when 'Bugfix'
+ metadata[:bugs] << t.delete_prefix('Bugfix: ')
+ when 'Security'
+ metadata[:security] << t.delete_prefix('Security: ')
+ end
+ end
+
+ return metadata, latest_entry
+ end
+
+ def build_release_content
+ metadata, latest_entry = build_metadata
+ <<~FRONTMATTER
+ #{DIVIDER}
+ subject: Ruby agent
+ date: #{Date.today}
+ version: #{NewRelic::VERSION::STRING}
+ downloadLink: https://rubygems.org/downloads/newrelic_rpm-#{NewRelic::VERSION::STRING}.gem
+ features: #{metadata[:features]}
+ bugs: #{metadata[:bugs]}
+ security: #{metadata[:security]}
+ #{DIVIDER}
+
+ #{SUPPORT_STATEMENT}
+ #{latest_entry}
+ FRONTMATTER
+ end
+
+ def write_filename
+ "ruby-agent-#{NewRelic::VERSION::STRING.tr('.', '-')}.mdx"
+ end
+
+ def write_output_file
+ File.write(write_filename, build_release_content)
+ end
+end
+
+GenerateReleaseNotes.new.write_output_file
diff --git a/.gitignore b/.gitignore
index 4d7a7f20db..e9b456f626 100644
--- a/.gitignore
+++ b/.gitignore
@@ -40,3 +40,4 @@ vendor/
Brewfile.lock.json
.github/actions/simplecov-report/lib/
test/minitest/minitest_time_report
+gem_manifest_*.json
diff --git a/.rubocop.yml b/.rubocop.yml
index b477ec5c6c..f07ac203ad 100644
--- a/.rubocop.yml
+++ b/.rubocop.yml
@@ -66,7 +66,7 @@ Style/RedundantEach: # new in 1.38
Enabled: true
Style/RedundantInitialize: # new in 1.27
Enabled: true
-Style/RedundantStringEscape: # new in 1.37
+Style/RedundantStringEscape: # new in 1.37, 'pending' by default so enabled to make sure it's applied
Enabled: true
Style/YodaExpression: # new in 1.42
Enabled: true
@@ -140,7 +140,8 @@ Performance/StringIdentifierArgument: # new in 1.13
Enabled: true
Performance/StringInclude: # new in 1.7
Enabled: true
-
+Performance/Sum: # new in 1.8, pending so left enabled explicitly until 2.0
+ Enabled: true
# Old cops
@@ -1255,9 +1256,6 @@ Style/DocumentationMethod:
Style/DoubleCopDisableDirective:
Enabled: false
-Style/DoubleNegation:
- Enabled: false
-
Style/EachForSimpleLoop:
Enabled: true
@@ -1318,6 +1316,9 @@ Style/ExplicitBlockArgument:
Style/ExponentialNotation:
Enabled: false
+Style/FetchEnvVar:
+ Enabled: false
+
Style/FloatDivision:
Enabled: false
@@ -1781,17 +1782,6 @@ Style/StringConcatenation:
Style/StringHashKeys:
Enabled: false
-# Disabling for now
-Style/StringLiterals:
- Enabled: false
-# EnforcedStyle: double_quotes
-# ConsistentQuotesInMultiline: false
-
-# Disabling for now
-Style/StringLiteralsInInterpolation:
- Enabled: false
- # EnforcedStyle: double_quotes
-
Style/StringMethods:
Enabled: false
diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml
index eae2743522..a2a3c22df6 100644
--- a/.rubocop_todo.yml
+++ b/.rubocop_todo.yml
@@ -9,10 +9,11 @@
# Offense count: 422
# Configuration parameters: AllowedMethods, AllowedPatterns, IgnoredMethods, CountRepeatedAttributes.
Metrics/AbcSize:
- Max: 54
+ Max: 40
Exclude:
- - test/**/*
- infinite_tracing/test/**/*
+ - lib/new_relic/cli/commands/deployments.rb
+ - test/**/*
# This cop supports safe autocorrection (--autocorrect).
Minitest/AssertInDelta:
@@ -36,6 +37,7 @@ Minitest/DuplicateTestRun:
Minitest/EmptyLineBeforeAssertionMethods:
Exclude:
- 'test/new_relic/agent_test.rb'
+ - 'test/new_relic/cli/commands/deployments_test.rb'
# Offense count: 269
Minitest/MultipleAssertions:
@@ -57,44 +59,3 @@ Style/ConcatArrayLiterals:
Minitest/RefuteRespondTo:
Exclude:
- 'test/new_relic/cli/commands/deployments_test.rb'
-
-Minitest/EmptyLineBeforeAssertionMethods:
- Exclude:
- - 'test/new_relic/agent_test.rb'
- - 'test/new_relic/cli/commands/deployments_test.rb'
-
-# Offense count: 23
-# This cop supports safe autocorrection (--autocorrect).
-Performance/RegexpMatch:
- Enabled: false
-
-# Offense count: 1
-# This cop supports unsafe autocorrection (--autocorrect-all).
-# Configuration parameters: OnlySumOrWithInitialValue.
-Performance/Sum:
- Exclude:
- - 'lib/new_relic/agent/system_info.rb'
-
-# Offense count: 72
-# This cop supports unsafe autocorrection (--autocorrect-all).
-Performance/UnfreezeString:
- Enabled: false
-
-# Offense count: 21
-# This cop supports safe autocorrection (--autocorrect).
-# Configuration parameters: AllowedVars.
-Style/FetchEnvVar:
- Enabled: false
-
-# Offense count: 1
-# This cop supports safe autocorrection (--autocorrect).
-Style/RedundantStringEscape:
- Exclude:
- - 'test/new_relic/agent/logging_test.rb'
-
-# Offense count: 115
-# This cop supports unsafe autocorrection (--autocorrect-all).
-# Configuration parameters: ConvertCodeThatCanStartToReturnNil, AllowedMethods, MaxChainLength.
-# AllowedMethods: present?, blank?, presence, try, try!
-Style/SafeNavigation:
- Enabled: false
diff --git a/.simplecov b/.simplecov
index a8bb2cdb95..98eaabb7c0 100644
--- a/.simplecov
+++ b/.simplecov
@@ -10,6 +10,6 @@ end
SimpleCov.start do
enable_coverage(:branch)
SimpleCov.root(File.join(File.dirname(__FILE__), '/lib'))
- track_files("**/*.rb")
+ track_files('**/*.rb')
formatter(SimpleCov::Formatter::SimpleFormatter) if ENV['CI']
end
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4950388ae5..9f18fb19b1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,63 @@
# New Relic Ruby Agent Release Notes
+## v9.1.0
+
+ Version 9.1.0 of the agent delivers support for two new [errors inbox](https://docs.newrelic.com/docs/errors-inbox/errors-inbox/) features: error fingerprinting and user tracking, identifies the Amazon Timestream data store, removes Distributed Tracing warnings from agent logs when using Sidekiq, fixes bugs, and is tested against the recently released JRuby 9.4.2.0.
+
+- **Feature: Error fingerprinting - supply your own errors inbox group names**
+
+ Are your error occurrences grouped poorly? Set your own error fingerprint via a callback function. A new `set_error_group_callback` public API method has been added that will accept a user defined proc. The proc will be invoked for each noticed error and whenever it returns a string, that string will be used as the error group name for the error and will take precedence over any server-side grouping that takes place with the New Relic errors inbox. This gives users much greater control over the grouping of their errors.
+
+ The customer defined proc will be expected to receive exactly one input argument, a hash. The hash contains the following:
+
+ | Key | Value |
+ | ---------------------| ---------------------------------------------------------------------------- |
+ | `:error` | The Ruby error class instance. Offers `#class`, `#message`, and `#backtrace` |
+ | `:customAttributes` | Any customer defined custom attributes for the current transaction |
+ | `:'request.uri'` | The current request URI if available |
+ | `:'http.statusCode'` | The HTTP status code (200, 404, etc.) if available |
+ | `:'http.method'` | The HTTP method (GET, PUT, etc.) if available |
+ | `:'error.expected'` | Whether (true) or not (false) the error was expected |
+ | `:'options'` | The options hash passed to `NewRelic::Agent.notice_error` |
+
+ The callback only needs to be set once per initialization of the New Relic agent.
+
+ Example usage:
+
+ ```
+ proc = proc { |hash| "Access" if hash[:'http.statusCode'] == 401 }
+ NewRelic::Agent.set_error_group_callback(proc)
+ ```
+
+- **Feature: User tracking - associate errors with a user id**
+
+ You can now see the number of users impacted by an error group. Identify the end user with a new `set_user_id` public API method that will accept a string representation of a user id and associate that user id with the current transaction. Transactions and errors will then have a new `enduser.id` agent attribute associated with them. This will allow agent users to tag transactions and errors as belonging to given user ids in support of greater filtering and alerting capabilities.
+
+- **Identify Amazon Timestream when the amazon_timestream AR adapter is used**
+
+ When the agent sees the [activerecord-amazon-timestream-adapter](https://rubygems.org/gems/activerecord-amazon-timestream-adapter) gem being used, it will now identify the data store as "Timestream". Thanks very much to [@wagner](https://github.com/wagner) for contributing this enhancement! [PR#1872](https://github.com/newrelic/newrelic-ruby-agent/pull/1872)
+
+- **Bugfix: Remove Distributed Tracing related warnings from agent logs when headers are not present in Sidekiq**
+
+ Previously, the agent would log a warning to `newrelic_agent.log` every time it attempted to accept empty Distributed Tracing headers from Sidekiq jobs which could result in an excessive number of warnings. Now the agent will no longer create these warnings when using Sidekiq. [PR#1834](https://github.com/newrelic/newrelic-ruby-agent/pull/1834)
+
+- **Bugfix: Log request headers in debug-level logs instead of human-readable Objects**
+
+ Previously, the agent sometimes received children of the `NewRelic::Agent::HTTPClients::AbstractRequest` class as an argument when `NewRelic::Agent::Transaction::DistributedTracers#log_request_headers` was called. This caused debug-level log messages that print the request headers to show human-readable Objects (ex. `#`) instead of the request headers. Now, the hash of the request headers should always be logged. [PR#1839](https://github.com/newrelic/newrelic-ruby-agent/pull/1839)
+
+- **Bugfix: Fix undefined method `controller_path` logged in Action Controller Instrumentation**
+
+ Previously, the agent could log an error when trying to determine the metric name in the Action Controller instrumentation if the controller class did not respond to `controller_path`. This has been resolved and the agent will no longer call this method unless the class responds to it. Thank you to [@gsar](https://github.com/gsar) for letting us know about this issue. [PR#1844](https://github.com/newrelic/newrelic-ruby-agent/pull/1844)
+
+- **Bugfix: Fix Transaction#finish exception and decrease log level for related warning during async transactions**
+
+ Previously, the agent would raise a non-fatal error when a segment without a parent was unfinished when the transaction completed. This error was raised while constructing a `warn`-level log message. Now that Thread instrumentation is on by default, this log message emits more frequently and is less concerning. In cases where we see a Thread, Fiber, or concurrent-ruby segment in a transaction, the message will be degraded to a `debug`-level. Thanks to [@NielsKSchjoedt](https://github.com/NielsKSchjoedt) for creating the issue and [@boomer196](https://github.com/boomer196) for testing solutions. [PR#1876](https://github.com/newrelic/newrelic-ruby-agent/pull/1876)
+
+- **CI: Target JRuby 9.4.2.0**
+
+ The agent is now actively being tested against JRuby 9.4.2.0. NOTE that this release does not contain any non-CI related changes for JRuby. Old agent versions are still expected to work with newer JRubies and the newest agent version is still expected to work with older JRubies.
+
+
## v9.0.0
Version 9.0.0 of the agent removes several deprecated configuration options and API methods, enables Thread tracing by default, adds Fiber instrumentation, removes support for Ruby versions 2.2 and 2.3, removes instrumentation for several deprecated gems, changes how the API method `set_transaction_name` works, and updates `rails_defer_initialization` to be an environment variable only configuration option.
@@ -92,8 +150,8 @@
- HttpClient: 2.2.0 - 2.8.0
- HttpRb: 0.9.9 - 2.2.1
- Typhoeus: 0.5.3 - 1.2.x
- - Bunny: 2.0.x - 2.6.x
- - ActiveMerchant: 1.25.0 - 1.64.x
+ - Bunny: 2.0.x - 2.6.x
+ - ActiveMerchant: 1.25.0 - 1.64.x
- **Updated API method `set_transaction_name`**
diff --git a/Gemfile b/Gemfile
index 2a2ef94672..98632a9f23 100644
--- a/Gemfile
+++ b/Gemfile
@@ -3,4 +3,4 @@
# frozen_string_literal: true
source 'https://rubygems.org'
-gemspec name: "newrelic_rpm"
+gemspec name: 'newrelic_rpm'
diff --git a/Guardfile b/Guardfile
index 6d592c0ffb..05f2d9e1fa 100644
--- a/Guardfile
+++ b/Guardfile
@@ -1,10 +1,10 @@
# frozen_string_literal: true
require './test/multiverse/lib/multiverse/bundler_patch'
-test_folders = Dir.glob("test/new_relic/*").select { |f| File.directory?(f) }
-test_folders += Dir.glob("test/new_relic/**/*").select { |f| File.directory?(f) }
+test_folders = Dir.glob('test/new_relic/*').select { |f| File.directory?(f) }
+test_folders += Dir.glob('test/new_relic/**/*').select { |f| File.directory?(f) }
-rake_lib_path = Bundler.with_unbundled_env { `bundle exec gem which rake`.chomp.gsub("lib/rake.rb", "lib") }
+rake_lib_path = Bundler.with_unbundled_env { `bundle exec gem which rake`.chomp.gsub('lib/rake.rb', 'lib') }
ruby_options = %(-w -I"#{rake_lib_path}" "#{rake_lib_path}/rake/rake_test_loader.rb")
guard_options = {
@@ -17,10 +17,10 @@ guard_options = {
guard :minitest, guard_options do
watch(%r{^lib/(.+)\.rb$}) { |m| "test/#{m[1]}_test.rb" }
watch(%r{^test/.+_test\.rb$})
- watch(%r{^test/rum/.*}) { "test/new_relic/rack/browser_monitoring_test.rb" }
+ watch(%r{^test/rum/.*}) { 'test/new_relic/rack/browser_monitoring_test.rb' }
watch(%r{^test/fixtures/cross_agent_tests/distributed_tracing/(.+).json}) { |m| "test/new_relic/agent/distributed_tracing/#{m[1]}_cross_agent_test.rb" }
- watch('test/test_helper.rb') { "test/new_relic" }
- watch('test/agent_helper.rb') { "test/new_relic" }
- watch('lib/new_relic/agent/configuration/default_source.rb') { "test/new_relic/agent/configuration/orphan_configuration_test.rb" }
+ watch('test/test_helper.rb') { 'test/new_relic' }
+ watch('test/agent_helper.rb') { 'test/new_relic' }
+ watch('lib/new_relic/agent/configuration/default_source.rb') { 'test/new_relic/agent/configuration/orphan_configuration_test.rb' }
watch(%r{^lib/new_relic/agent/transaction/(.+).rb}) { |m| "test/new_relic/agent/distributed_tracing/#{m[1]}_cross_agent_test.rb" }
end
diff --git a/README.md b/README.md
index 1545d17090..a8d53ffba9 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,4 @@
-[![Community Plus header](https://github.com/newrelic/opensource-website/raw/main/src/images/categories/Community_Plus.png)](https://opensource.newrelic.com/oss-category/#community-plus)
-
+
# New Relic Ruby Agent
diff --git a/Rakefile b/Rakefile
index 3792702104..fe15cc68a7 100644
--- a/Rakefile
+++ b/Rakefile
@@ -15,11 +15,11 @@ task :default => :test
task :test => ['test:newrelic']
namespace :test do
- desc "Run all tests"
+ desc 'Run all tests'
task :all => %w[newrelic multiverse all_compatible_envs]
agent_home = File.expand_path(File.dirname(__FILE__))
- desc "Run agent performance tests"
+ desc 'Run agent performance tests'
task :performance, [:suite, :name] => [] do |t, args|
require File.expand_path(File.join(File.dirname(__FILE__), 'test', 'performance', 'lib', 'performance'))
options = {}
@@ -28,13 +28,13 @@ namespace :test do
Performance::Runner.new(options).run_and_report
end
- desc "Run agent within existing mini environment(s): env[name1,name2,name3,etc.]"
+ desc 'Run agent within existing mini environment(s): env[name1,name2,name3,etc.]'
task :env do |t, args|
require File.expand_path(File.join(File.dirname(__FILE__), 'test', 'environments', 'lib', 'environments', 'runner'))
Environments::Runner.new(args.to_a).run_and_report
end
- desc "Run all mini environment tests known to work with the current Ruby version"
+ desc 'Run all mini environment tests known to work with the current Ruby version'
task :all_compatible_envs do |t, args|
require File.expand_path(File.join(File.dirname(__FILE__), 'test', 'helpers', 'ruby_rails_mappings'))
rails_versions = rails_versions_for_ruby_version(RUBY_VERSION)
@@ -62,10 +62,10 @@ task :record_build, [:build_number, :stage] do |t, args|
build_string = args.build_number
build_string << ".#{args.stage}" unless args.stage.nil? || args.stage.empty?
- gitsha = File.exist?(".git") ? `git rev-parse HEAD` : "Unknown"
+ gitsha = File.exist?('.git') ? `git rev-parse HEAD` : 'Unknown'
gitsha.chomp!
- File.open("lib/new_relic/build.rb", "w") do |f|
+ File.open('lib/new_relic/build.rb', 'w') do |f|
f.write("# GITSHA: #{gitsha}\n")
f.write("module NewRelic; module VERSION; BUILD='#{build_string}'; end; end\n")
end
@@ -93,14 +93,14 @@ task :update_ca_bundle do |t|
bundle_last_update = `cd #{ca_bundle_path} && git show -s --format=%ci HEAD`
puts "Source CA bundle last updated #{bundle_last_update}"
- bundle_path = "cert/cacert.pem"
+ bundle_path = 'cert/cacert.pem'
cert_paths = []
Dir.glob("#{ca_bundle_path}/*.pem").each { |p| cert_paths << p }
cert_paths.sort!
puts "Writing #{cert_paths.size} certs to bundle at #{bundle_path}..."
- File.open(bundle_path, "w") do |f|
+ File.open(bundle_path, 'w') do |f|
cert_paths.each do |cert_path|
cert_name = File.basename(cert_path, '.pem')
puts "Adding #{cert_name}"
diff --git a/Thorfile b/Thorfile
index b883c3c820..113ead294e 100644
--- a/Thorfile
+++ b/Thorfile
@@ -2,4 +2,4 @@
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
# frozen_string_literal: true
-Dir["./lib/tasks/**/*.thor"].sort.each { |f| load f }
+Dir['./lib/tasks/**/*.thor'].sort.each { |f| load f }
diff --git a/bin/nrdebug b/bin/nrdebug
index 33460a9d53..d998c4e56d 100755
--- a/bin/nrdebug
+++ b/bin/nrdebug
@@ -96,7 +96,7 @@ class LinuxProcessDataProvider < ProcessDataProvider
end
def procline
- File.read(proc_path('cmdline')).tr("\000", " ")
+ File.read(proc_path('cmdline')).tr("\000", ' ')
end
def environment
@@ -189,7 +189,7 @@ class ProcessReport
def open
if @path
- File.open(@path, "w") do |f|
+ File.open(@path, 'w') do |f|
yield(f)
end
else
@@ -216,16 +216,16 @@ class ProcessReport
section(f) do
c_backtraces, ruby_backtraces = @target.gather_backtraces
- if c_backtraces =~ /could not attach/i
- fail("Failed to attach to target process. Please try again with sudo.")
+ if /could not attach/i.match?(c_backtraces)
+ fail('Failed to attach to target process. Please try again with sudo.')
end
- section(f, "C Backtraces") { c_backtraces }
- section(f, "Ruby Backtrace(s)") { ruby_backtraces }
+ section(f, 'C Backtraces') { c_backtraces }
+ section(f, 'Ruby Backtrace(s)') { ruby_backtraces }
end
- section(f, "Open files") { @target.open_files }
- section(f, "Log") do
+ section(f, 'Open files') { @target.open_files }
+ section(f, 'Log') do
commands = Logger.messages.map { |(_, msg)| msg }
commands.join("\n")
end
@@ -235,14 +235,14 @@ class ProcessReport
private
def add_environment_sections(handle)
- section(handle, "Time") { Time.now }
- section(handle, "PID") { @target.pid }
- section(handle, "Command") { @target.procline }
- section(handle, "RSS") { @target.rss }
- section(handle, "CPU") { @target.cpu }
- section(handle, "Parent PID") { @target.ppid }
- section(handle, "OS") { ShellWrapper.execute('uname -a') }
- section(handle, "Environment") { @target.environment }
+ section(handle, 'Time') { Time.now }
+ section(handle, 'PID') { @target.pid }
+ section(handle, 'Command') { @target.procline }
+ section(handle, 'RSS') { @target.rss }
+ section(handle, 'CPU') { @target.cpu }
+ section(handle, 'Parent PID') { @target.ppid }
+ section(handle, 'OS') { ShellWrapper.execute('uname -a') }
+ section(handle, 'Environment') { @target.environment }
end
end
@@ -270,10 +270,10 @@ def prompt_for_confirmation(target_pid, target_cmd)
end
target_pid = ARGV[0]
-fail("Please provide a PID for the target process", :usage => true) unless target_pid
+fail('Please provide a PID for the target process', :usage => true) unless target_pid
gdb_path = `which gdb`
-fail("Could not find gdb, please ensure it is installed and in your PATH") if gdb_path.empty?
+fail('Could not find gdb, please ensure it is installed and in your PATH') if gdb_path.empty?
target = RubyProcess.new(target_pid)
if !target.attachable?
@@ -298,5 +298,5 @@ report.generate
puts "Generated '#{report_filename}'"
puts ''
-puts "Please examine the output file for potentially sensitive information and"
-puts "remove it before sharing this file with anyone."
+puts 'Please examine the output file for potentially sensitive information and'
+puts 'remove it before sharing this file with anyone.'
diff --git a/infinite_tracing/Gemfile b/infinite_tracing/Gemfile
index 1522c3b61b..a0c78fdf10 100644
--- a/infinite_tracing/Gemfile
+++ b/infinite_tracing/Gemfile
@@ -4,7 +4,7 @@
source 'https://rubygems.org'
-gemspec name: "newrelic-infinite_tracing"
+gemspec name: 'newrelic-infinite_tracing'
group :development do
gem 'newrelic_rpm', path: '..'
diff --git a/infinite_tracing/Rakefile b/infinite_tracing/Rakefile
index 5568ed0d73..b1e2c9cc52 100644
--- a/infinite_tracing/Rakefile
+++ b/infinite_tracing/Rakefile
@@ -23,6 +23,6 @@ Rake::TestTask.new do |t|
t.libs << "#{ROOT}/test"
t.libs << "#{ROOT}/lib"
- t.pattern = Array(file_pattern).join(",")
- t.verbose = ENV["VERBOSE"]
+ t.pattern = Array(file_pattern).join(',')
+ t.verbose = ENV['VERBOSE']
end
diff --git a/infinite_tracing/lib/infinite_tracing/agent_integrations.rb b/infinite_tracing/lib/infinite_tracing/agent_integrations.rb
index f5f307eebc..3b00d5f1cc 100644
--- a/infinite_tracing/lib/infinite_tracing/agent_integrations.rb
+++ b/infinite_tracing/lib/infinite_tracing/agent_integrations.rb
@@ -5,7 +5,7 @@
module NewRelic::Agent
module InfiniteTracing
if Config.enabled? || Config.test_framework?
- NewRelic::Agent.logger.debug("Integrating Infinite Tracer with Agent")
+ NewRelic::Agent.logger.debug('Integrating Infinite Tracer with Agent')
require_relative 'agent_integrations/agent'
require_relative 'agent_integrations/segment'
@@ -13,7 +13,7 @@ module InfiniteTracing
require_relative 'agent_integrations/external_request_segment'
else
- NewRelic::Agent.logger.debug("Skipped Integrating Infinite Tracer with Agent")
+ NewRelic::Agent.logger.debug('Skipped Integrating Infinite Tracer with Agent')
end
end
end
diff --git a/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb b/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb
index e05e5d1954..5b1ff268c5 100644
--- a/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb
+++ b/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb
@@ -3,7 +3,7 @@
# frozen_string_literal: true
module NewRelic::Agent
- NewRelic::Agent.logger.debug("Installing Infinite Tracer in Agent")
+ NewRelic::Agent.logger.debug('Installing Infinite Tracer in Agent')
Agent.class_eval do
def new_infinite_tracer
@@ -11,7 +11,7 @@ def new_infinite_tracer
# entire start up process for the Agent.
InfiniteTracing::Client.new.tap do |client|
@infinite_tracer_thread = InfiniteTracing::Worker.new(:infinite_tracer) do
- NewRelic::Agent.logger.debug("Opening Infinite Tracer Stream with gRPC server")
+ NewRelic::Agent.logger.debug('Opening Infinite Tracer Stream with gRPC server')
client.start_streaming
end
end
@@ -23,7 +23,7 @@ def new_infinite_tracer
def handle_force_restart(error)
::NewRelic::Agent.logger.debug(error.message)
drop_buffered_data
- @service.force_restart if @service
+ @service&.force_restart
@connect_state = :pending
close_infinite_tracer
sleep(30)
@@ -31,7 +31,7 @@ def handle_force_restart(error)
# Whenever we reconnect, close and restart
def close_infinite_tracer
- NewRelic::Agent.logger.debug("Closing infinite tracer threads")
+ NewRelic::Agent.logger.debug('Closing infinite tracer threads')
return unless @infinite_tracer_thread
@infinite_tracer_thread.join
diff --git a/infinite_tracing/lib/infinite_tracing/client.rb b/infinite_tracing/lib/infinite_tracing/client.rb
index 2a8585d55a..56614463ad 100644
--- a/infinite_tracing/lib/infinite_tracing/client.rb
+++ b/infinite_tracing/lib/infinite_tracing/client.rb
@@ -55,7 +55,7 @@ def flush
# Turns camelcase base class name into upper snake case version of the name.
def formatted_class_name(class_name)
- class_name = class_name.split(":")[-1]
+ class_name = class_name.split(':')[-1]
(class_name.gsub!(/(.)([A-Z])/, '\1_\2') || class_name).upcase
end
@@ -73,7 +73,7 @@ def record_error_metrics_and_log(error)
else
NewRelic::Agent.record_metric(GRPC_OTHER_ERROR_METRIC, 0.0)
end
- NewRelic::Agent.logger.warn("gRPC response error received.", error)
+ NewRelic::Agent.logger.warn('gRPC response error received.', error)
end
def handle_error(error)
@@ -99,8 +99,8 @@ def suspended?
# server and re-establish the gRPC bi-directional stream. Useful for the server
# to initiate a load-balancing scheme.
def handle_close
- NewRelic::Agent.logger.debug("The gRPC Trace Observer closed the stream with OK response. " \
- "Restarting the stream.")
+ NewRelic::Agent.logger.debug('The gRPC Trace Observer closed the stream with OK response. ' \
+ 'Restarting the stream.')
start_streaming
end
@@ -113,8 +113,8 @@ def suspend
@lock.synchronize do
@suspended = true
@buffer = new_streaming_buffer
- NewRelic::Agent.logger.warn("The Trace Observer host signaled to suspend streaming span events. " \
- "No more span events will be sent during this session.")
+ NewRelic::Agent.logger.warn('The Trace Observer host signaled to suspend streaming span events. ' \
+ 'No more span events will be sent during this session.')
end
end
diff --git a/infinite_tracing/lib/infinite_tracing/config.rb b/infinite_tracing/lib/infinite_tracing/config.rb
index 46300ec70e..97c9b03eae 100644
--- a/infinite_tracing/lib/infinite_tracing/config.rb
+++ b/infinite_tracing/lib/infinite_tracing/config.rb
@@ -10,7 +10,7 @@ module Config
COMPRESSION_LEVEL_DISABLED = :none
COMPRESSION_LEVEL_DEFAULT = :high
COMPRESSION_LEVEL_LIST = %i[none low medium high].freeze
- TRACE_OBSERVER_NOT_CONFIGURED_ERROR = "Trace Observer host not configured!"
+ TRACE_OBSERVER_NOT_CONFIGURED_ERROR = 'Trace Observer host not configured!'
# We only want to load the infinite tracing gem's files when
# a) we're inside test framework and running tests
@@ -64,7 +64,7 @@ def trace_observer_host
# is overridden by the presence of the port on the host entry.
def port_from_host_entry
port_str = NewRelic::Agent.config[:'infinite_tracing.trace_observer.host'].scan(%r{:(\d+)$}).flatten
- if port = (port_str[0] and port_str[0].to_i)
+ if port = port_str[0]&.to_i
NewRelic::Agent.logger.warn(":'infinite_tracing.trace_observer.port' is ignored if present because :'infinite_tracing.trace_observer.host' specifies the port")
return port
end
diff --git a/infinite_tracing/lib/infinite_tracing/connection.rb b/infinite_tracing/lib/infinite_tracing/connection.rb
index 95667639b6..30c783b5d3 100644
--- a/infinite_tracing/lib/infinite_tracing/connection.rb
+++ b/infinite_tracing/lib/infinite_tracing/connection.rb
@@ -31,7 +31,7 @@ class Connection
Connection.instance.notify_agent_started
rescue => error
NewRelic::Agent.logger.error( \
- "Error during notify :server_source_configuration_added event",
+ 'Error during notify :server_source_configuration_added event',
error
)
end
@@ -102,8 +102,8 @@ def metadata
@lock.synchronize do
@metadata = {
- "license_key" => license_key,
- "agent_run_token" => agent_id
+ 'license_key' => license_key,
+ 'agent_run_token' => agent_id
}
@metadata.merge!(request_headers_map)
merge_gzip_metadata
@@ -168,7 +168,7 @@ def with_reconnection_backoff(exponential_backoff = true, &block)
yield
rescue => exception
retry_connection_period = retry_connection_period(exponential_backoff)
- ::NewRelic::Agent.logger.error("Error establishing connection with infinite tracing service:", exception)
+ ::NewRelic::Agent.logger.error('Error establishing connection with infinite tracing service:', exception)
::NewRelic::Agent.logger.info("Will re-attempt infinite tracing connection in #{retry_connection_period} seconds")
sleep(retry_connection_period)
note_connect_failure
diff --git a/infinite_tracing/lib/infinite_tracing/constants.rb b/infinite_tracing/lib/infinite_tracing/constants.rb
index 6f9780e0c8..c76b8613a8 100644
--- a/infinite_tracing/lib/infinite_tracing/constants.rb
+++ b/infinite_tracing/lib/infinite_tracing/constants.rb
@@ -5,7 +5,7 @@
module NewRelic::Agent
module InfiniteTracing
module Constants
- SUPPORTABILITY_PREFIX = "Supportability/InfiniteTracing/Span"
+ SUPPORTABILITY_PREFIX = 'Supportability/InfiniteTracing/Span'
SPANS_SEEN_METRIC = "#{SUPPORTABILITY_PREFIX}/Seen"
SPANS_SENT_METRIC = "#{SUPPORTABILITY_PREFIX}/Sent"
@@ -13,7 +13,7 @@ module Constants
RESPONSE_ERROR_METRIC = "#{SUPPORTABILITY_PREFIX}/Response/Error"
GRPC_ERROR_NAME_METRIC = "#{SUPPORTABILITY_PREFIX}/gRPC/%s"
- GRPC_OTHER_ERROR_METRIC = GRPC_ERROR_NAME_METRIC % "Other"
+ GRPC_OTHER_ERROR_METRIC = GRPC_ERROR_NAME_METRIC % 'Other'
end
end
end
diff --git a/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb b/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb
index d1fcdc8848..b2b080edfe 100644
--- a/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb
+++ b/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb
@@ -6,16 +6,16 @@
# source: infinite_tracing.proto
Google::Protobuf::DescriptorPool.generated_pool.build do
- add_message "com.newrelic.trace.v1.SpanBatch" do
- repeated :spans, :message, 1, "com.newrelic.trace.v1.Span"
+ add_message 'com.newrelic.trace.v1.SpanBatch' do
+ repeated :spans, :message, 1, 'com.newrelic.trace.v1.Span'
end
- add_message "com.newrelic.trace.v1.Span" do
+ add_message 'com.newrelic.trace.v1.Span' do
optional :trace_id, :string, 1
- map :intrinsics, :string, :message, 2, "com.newrelic.trace.v1.AttributeValue"
- map :user_attributes, :string, :message, 3, "com.newrelic.trace.v1.AttributeValue"
- map :agent_attributes, :string, :message, 4, "com.newrelic.trace.v1.AttributeValue"
+ map :intrinsics, :string, :message, 2, 'com.newrelic.trace.v1.AttributeValue'
+ map :user_attributes, :string, :message, 3, 'com.newrelic.trace.v1.AttributeValue'
+ map :agent_attributes, :string, :message, 4, 'com.newrelic.trace.v1.AttributeValue'
end
- add_message "com.newrelic.trace.v1.AttributeValue" do
+ add_message 'com.newrelic.trace.v1.AttributeValue' do
oneof :value do
optional :string_value, :string, 1
optional :bool_value, :bool, 2
@@ -23,7 +23,7 @@
optional :double_value, :double, 4
end
end
- add_message "com.newrelic.trace.v1.RecordStatus" do
+ add_message 'com.newrelic.trace.v1.RecordStatus' do
optional :messages_seen, :uint64, 1
end
end
@@ -32,10 +32,10 @@ module Com
module Newrelic
module Trace
module V1
- SpanBatch = Google::Protobuf::DescriptorPool.generated_pool.lookup("com.newrelic.trace.v1.SpanBatch").msgclass
- Span = Google::Protobuf::DescriptorPool.generated_pool.lookup("com.newrelic.trace.v1.Span").msgclass
- AttributeValue = Google::Protobuf::DescriptorPool.generated_pool.lookup("com.newrelic.trace.v1.AttributeValue").msgclass
- RecordStatus = Google::Protobuf::DescriptorPool.generated_pool.lookup("com.newrelic.trace.v1.RecordStatus").msgclass
+ SpanBatch = Google::Protobuf::DescriptorPool.generated_pool.lookup('com.newrelic.trace.v1.SpanBatch').msgclass
+ Span = Google::Protobuf::DescriptorPool.generated_pool.lookup('com.newrelic.trace.v1.Span').msgclass
+ AttributeValue = Google::Protobuf::DescriptorPool.generated_pool.lookup('com.newrelic.trace.v1.AttributeValue').msgclass
+ RecordStatus = Google::Protobuf::DescriptorPool.generated_pool.lookup('com.newrelic.trace.v1.RecordStatus').msgclass
end
end
end
diff --git a/infinite_tracing/lib/infinite_tracing/record_status_handler.rb b/infinite_tracing/lib/infinite_tracing/record_status_handler.rb
index 0946509ee0..2775d814dd 100644
--- a/infinite_tracing/lib/infinite_tracing/record_status_handler.rb
+++ b/infinite_tracing/lib/infinite_tracing/record_status_handler.rb
@@ -21,7 +21,7 @@ def stop
return if @worker.nil?
@lock.synchronize do
- NewRelic::Agent.logger.debug("gRPC Stopping Response Handler")
+ NewRelic::Agent.logger.debug('gRPC Stopping Response Handler')
@worker.stop
@worker = nil
end
@@ -43,13 +43,13 @@ def handle_response
def start_handler
Worker.new(self.class.name) do
handle_response
- NewRelic::Agent.logger.debug("gRPC Infinite Tracer Observer closed the stream")
+ NewRelic::Agent.logger.debug('gRPC Infinite Tracer Observer closed the stream')
@client.handle_close
rescue => error
@client.handle_error(error)
end
rescue => error
- NewRelic::Agent.logger.error("gRPC Worker Error", error)
+ NewRelic::Agent.logger.error('gRPC Worker Error', error)
end
end
end
diff --git a/infinite_tracing/lib/infinite_tracing/transformer.rb b/infinite_tracing/lib/infinite_tracing/transformer.rb
index ba4a0ebc24..be6301fd99 100644
--- a/infinite_tracing/lib/infinite_tracing/transformer.rb
+++ b/infinite_tracing/lib/infinite_tracing/transformer.rb
@@ -10,10 +10,10 @@ module Transformer
def transform(span_event)
intrinsics, user_attributes, agent_attributes = span_event
{
- "trace_id" => intrinsics[NewRelic::Agent::SpanEventPrimitive::TRACE_ID_KEY],
- "intrinsics" => hash_to_attributes(intrinsics),
- "user_attributes" => hash_to_attributes(user_attributes),
- "agent_attributes" => hash_to_attributes(agent_attributes)
+ 'trace_id' => intrinsics[NewRelic::Agent::SpanEventPrimitive::TRACE_ID_KEY],
+ 'intrinsics' => hash_to_attributes(intrinsics),
+ 'user_attributes' => hash_to_attributes(user_attributes),
+ 'agent_attributes' => hash_to_attributes(agent_attributes)
}
end
diff --git a/infinite_tracing/lib/infinite_tracing/worker.rb b/infinite_tracing/lib/infinite_tracing/worker.rb
index 34e45ec861..b460be1d3c 100644
--- a/infinite_tracing/lib/infinite_tracing/worker.rb
+++ b/infinite_tracing/lib/infinite_tracing/worker.rb
@@ -21,12 +21,12 @@ def initialize(name, &job)
end
def status
- return "error" if error?
+ return 'error' if error?
@lock.synchronize do
- return "stopped" if @worker_thread.nil?
+ return 'stopped' if @worker_thread.nil?
- @worker_thread.status || "idle"
+ @worker_thread.status || 'idle'
end
end
@@ -55,7 +55,7 @@ def stop
def start_thread
NewRelic::Agent.logger.debug("starting worker #{@name} thread...")
- @worker_thread = NewRelic::Agent::Threading::AgentThread.create("infinite_tracing_worker") do
+ @worker_thread = NewRelic::Agent::Threading::AgentThread.create('infinite_tracing_worker') do
catch(:exit) do
begin
@job.call
@@ -67,7 +67,7 @@ def start_thread
end
@worker_thread.abort_on_exception = true
if @worker_thread.respond_to?(:report_on_exception)
- @worker_thread.report_on_exception = NewRelic::Agent.config[:log_level] == "debug"
+ @worker_thread.report_on_exception = NewRelic::Agent.config[:log_level] == 'debug'
end
end
end
diff --git a/infinite_tracing/lib/newrelic/infinite_tracing.rb b/infinite_tracing/lib/newrelic/infinite_tracing.rb
index b07d5c6f96..4f5bbf02ce 100644
--- a/infinite_tracing/lib/newrelic/infinite_tracing.rb
+++ b/infinite_tracing/lib/newrelic/infinite_tracing.rb
@@ -8,7 +8,7 @@
require 'newrelic_rpm'
-NewRelic::Agent.logger.debug("Detected New Relic Infinite Tracing Gem")
+NewRelic::Agent.logger.debug('Detected New Relic Infinite Tracing Gem')
require 'infinite_tracing/version'
require 'infinite_tracing/config'
@@ -21,7 +21,7 @@
end
executes do
- NewRelic::Agent.logger.debug("Loading New Relic Infinite Tracing Library")
+ NewRelic::Agent.logger.debug('Loading New Relic Infinite Tracing Library')
require 'infinite_tracing/proto'
diff --git a/infinite_tracing/newrelic-infinite_tracing.gemspec b/infinite_tracing/newrelic-infinite_tracing.gemspec
index 3a6c97f9ba..0f7bb2e6b2 100644
--- a/infinite_tracing/newrelic-infinite_tracing.gemspec
+++ b/infinite_tracing/newrelic-infinite_tracing.gemspec
@@ -22,17 +22,17 @@ Gem::Specification.new do |s|
end
shared_files = [
- "../LICENSE",
- "../CONTRIBUTING.md"
+ '../LICENSE',
+ '../CONTRIBUTING.md'
]
self.copy_files(shared_files)
- s.name = "newrelic-infinite_tracing"
+ s.name = 'newrelic-infinite_tracing'
s.version = NewRelic::VERSION::STRING
s.required_ruby_version = '>= 2.5.0'
- s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to?(:required_rubygems_version=)
- s.authors = ["Tanna McClure", "Kayla Reopelle", "James Bunch", "Hannah Ramadan"]
+ s.required_rubygems_version = Gem::Requirement.new('> 1.3.1') if s.respond_to?(:required_rubygems_version=)
+ s.authors = ['Tanna McClure', 'Kayla Reopelle', 'James Bunch', 'Hannah Ramadan']
s.licenses = ['Apache-2.0']
s.description = <<~EOS
The New Relic Ruby agent requires the gem newrelic_rpm, and it includes distributed
@@ -49,11 +49,11 @@ Gem::Specification.new do |s|
Gem or plugin, hosted on https://github.com/newrelic/newrelic-ruby-agent/
EOS
- s.email = "support@newrelic.com"
+ s.email = 'support@newrelic.com'
s.executables = []
s.extra_rdoc_files = [
- "CHANGELOG.md",
- "LICENSE"
+ 'CHANGELOG.md',
+ 'LICENSE'
]
s.metadata = {
@@ -61,15 +61,15 @@ Gem::Specification.new do |s|
'changelog_uri' => 'https://github.com/newrelic/newrelic-ruby-agent/blob/main/infinite_tracing/CHANGELOG.md',
'documentation_uri' => 'https://docs.newrelic.com/docs/agents/ruby-agent',
'source_code_uri' => 'https://github.com/newrelic/newrelic-ruby-agent',
- "homepage_uri" => "https://newrelic.com/products/edge-infinite-tracing"
+ 'homepage_uri' => 'https://newrelic.com/products/edge-infinite-tracing'
}
file_list = `git ls-files . -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/(?!agent_helper.rb)}) }
s.files = file_list
- s.homepage = "https://github.com/newrelic/newrelic-ruby-agent/tree/main/infinite_tracing"
+ s.homepage = 'https://github.com/newrelic/newrelic-ruby-agent/tree/main/infinite_tracing'
s.require_paths = %w[lib infinite_tracing]
- s.summary = "New Relic Infinite Tracing for the Ruby agent"
+ s.summary = 'New Relic Infinite Tracing for the Ruby agent'
s.add_dependency 'newrelic_rpm', NewRelic::VERSION::STRING
s.add_dependency 'grpc', '~> 1.34'
@@ -87,5 +87,5 @@ Gem::Specification.new do |s|
s.add_development_dependency 'bundler'
s.add_development_dependency 'simplecov'
- s.add_development_dependency 'grpc-tools', "~> 1.14"
+ s.add_development_dependency 'grpc-tools', '~> 1.14'
end
diff --git a/infinite_tracing/tasks/helpers/license.rb b/infinite_tracing/tasks/helpers/license.rb
index 5c5892badc..191f57babb 100644
--- a/infinite_tracing/tasks/helpers/license.rb
+++ b/infinite_tracing/tasks/helpers/license.rb
@@ -6,14 +6,14 @@ module License
def extract_license_terms(file_contents)
text = []
text << file_contents.shift while !file_contents.empty? && file_contents[0] =~ /^#/
- text << ""
+ text << ''
text
end
def add_license_preamble_and_remove_requires(output_path)
gemspec_path = File.expand_path(File.join(output_path, '..', '..', '..', '..', '..'))
- license_terms = extract_license_terms(File.readlines(File.join(gemspec_path, "Gemfile")))
- Dir.glob(File.join(output_path, "*.rb")) do |filename|
+ license_terms = extract_license_terms(File.readlines(File.join(gemspec_path, 'Gemfile')))
+ Dir.glob(File.join(output_path, '*.rb')) do |filename|
contents = File.readlines(filename)
contents.reject! { |r| r =~ /^\s*require\s.*$/ }
File.open(filename, 'w') do |output|
diff --git a/infinite_tracing/tasks/proto.rake b/infinite_tracing/tasks/proto.rake
index 27f3771546..4024ec35b0 100644
--- a/infinite_tracing/tasks/proto.rake
+++ b/infinite_tracing/tasks/proto.rake
@@ -6,25 +6,25 @@ require_relative 'helpers/license'
include License
namespace :proto do
- desc "Generate proto files"
+ desc 'Generate proto files'
task :generate do
- gem_folder = File.expand_path(File.join(File.dirname(__FILE__), ".."))
- proto_filename = File.join(gem_folder, "lib", "new_relic", "proto", "infinite_tracing.proto")
- output_path = File.join(gem_folder, "lib", "new_relic", "infinite_tracing", "proto")
+ gem_folder = File.expand_path(File.join(File.dirname(__FILE__), '..'))
+ proto_filename = File.join(gem_folder, 'lib', 'new_relic', 'proto', 'infinite_tracing.proto')
+ output_path = File.join(gem_folder, 'lib', 'new_relic', 'infinite_tracing', 'proto')
FileUtils.mkdir_p(output_path)
cmd = [
- "grpc_tools_ruby_protoc",
+ 'grpc_tools_ruby_protoc',
"-I#{gem_folder}/lib/new_relic/proto",
"--ruby_out=#{output_path}",
"--grpc_out=#{output_path} #{proto_filename}"
- ].join(" ")
+ ].join(' ')
if system(cmd)
- puts "Proto file generated!"
+ puts 'Proto file generated!'
add_license_preamble_and_remove_requires(output_path)
else
- puts "Failed to generate proto file."
+ puts 'Failed to generate proto file.'
end
end
end
diff --git a/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb b/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb
index 8c97696c65..1acd0701fc 100644
--- a/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb
+++ b/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb
@@ -11,7 +11,7 @@ class AgentIntegrationTest < Minitest::Test
include FakeTraceObserverHelpers
def test_injects_infinite_tracer
- assert ::NewRelic::Agent.instance, "expected to get an Agent instance"
+ assert ::NewRelic::Agent.instance, 'expected to get an Agent instance'
assert ::NewRelic::Agent.instance.infinite_tracer
end
diff --git a/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb b/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb
index 133ef979ba..a967142dcd 100644
--- a/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb
+++ b/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb
@@ -17,19 +17,19 @@ def test_sampled_segment_records_span_event
sampled = nil
priority = nil
timestamp = nil
- sql_statement = "select * from table"
+ sql_statement = 'select * from table'
span_events = generate_and_stream_segments do
in_web_transaction('wat') do |txn|
txn.stubs(:sampled?).returns(true)
segment = Tracer.start_datastore_segment(
- product: "SQLite",
- collection: "Blahg",
- operation: "select",
- host: "rachel.foo",
+ product: 'SQLite',
+ collection: 'Blahg',
+ operation: 'select',
+ host: 'rachel.foo',
port_path_or_id: 1337807,
- database_name: "calzone_zone"
+ database_name: 'calzone_zone'
)
segment.notice_sql(sql_statement)
@@ -83,8 +83,8 @@ def test_non_sampled_segment_does_record_span_event
txn.stubs(:sampled?).returns(false)
segment = Tracer.start_datastore_segment(
- product: "SQLite",
- operation: "select",
+ product: 'SQLite',
+ operation: 'select',
port_path_or_id: 1337807
)
@@ -105,8 +105,8 @@ def test_ignored_transaction_does_not_record_span_event
txn.stubs(:ignore?).returns(true)
segment = Tracer.start_datastore_segment(
- product: "SQLite",
- operation: "select",
+ product: 'SQLite',
+ operation: 'select',
port_path_or_id: 1337807
)
diff --git a/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb b/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb
index 8e94b43869..548b0f062c 100644
--- a/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb
+++ b/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb
@@ -24,9 +24,9 @@ def test_sampled_external_records_span_event
txn.stubs(:sampled?).returns(true)
segment = Transaction::ExternalRequestSegment.new( \
- "Typhoeus",
- "http://remotehost.com/blogs/index",
- "GET"
+ 'Typhoeus',
+ 'http://remotehost.com/blogs/index',
+ 'GET'
)
txn.add_segment(segment)
@@ -75,9 +75,9 @@ def test_non_sampled_segment_does_record_span_event
txn.stubs(:sampled?).returns(false)
segment = Transaction::ExternalRequestSegment.new( \
- "Typhoeus",
- "http://remotehost.com/blogs/index",
- "GET"
+ 'Typhoeus',
+ 'http://remotehost.com/blogs/index',
+ 'GET'
)
txn.add_segment(segment)
@@ -98,9 +98,9 @@ def test_ignored_transaction_does_not_record_span_event
txn.stubs(:ignore?).returns(true)
segment = Transaction::ExternalRequestSegment.new( \
- "Typhoeus",
- "http://remotehost.com/blogs/index",
- "GET"
+ 'Typhoeus',
+ 'http://remotehost.com/blogs/index',
+ 'GET'
)
txn.add_segment(segment)
diff --git a/infinite_tracing/test/infinite_tracing/channel_test.rb b/infinite_tracing/test/infinite_tracing/channel_test.rb
index 53baf20940..d717411a9a 100644
--- a/infinite_tracing/test/infinite_tracing/channel_test.rb
+++ b/infinite_tracing/test/infinite_tracing/channel_test.rb
@@ -12,7 +12,7 @@ def local_config
{
:'distributed_tracing.enabled' => true,
:'span_events.enabled' => true,
- :'infinite_tracing.trace_observer.host' => "localhost:80"
+ :'infinite_tracing.trace_observer.host' => 'localhost:80'
}
end
@@ -20,7 +20,7 @@ def remote_config
{
:'distributed_tracing.enabled' => true,
:'span_events.enabled' => true,
- :'infinite_tracing.trace_observer.host' => "https://example.com"
+ :'infinite_tracing.trace_observer.host' => 'https://example.com'
}
end
@@ -31,7 +31,7 @@ def test_channel_is_secure_for_remote_host
channel = Channel.new
credentials = channel.send(:credentials)
- assert_equal "example.com:443", channel.send(:host_and_port)
+ assert_equal 'example.com:443', channel.send(:host_and_port)
assert_kind_of GRPC::Core::ChannelCredentials, credentials
end
ensure
@@ -42,14 +42,14 @@ def test_channel_is_really_secure_for_remote_host
Config.stubs(:test_framework?).returns(false)
# HTTP instead of HTTPS...
insecure_remote_config = remote_config.merge({
- :'infinite_tracing.trace_observer.host' => "http://example.com"
+ :'infinite_tracing.trace_observer.host' => 'http://example.com'
})
with_config(insecure_remote_config) do
channel = Channel.new
credentials = channel.send(:credentials)
- assert_equal "example.com:443", channel.send(:host_and_port)
+ assert_equal 'example.com:443', channel.send(:host_and_port)
assert_kind_of GRPC::Core::ChannelCredentials, credentials
end
ensure
diff --git a/infinite_tracing/test/infinite_tracing/client_test.rb b/infinite_tracing/test/infinite_tracing/client_test.rb
index 7c302d86ba..72a5de9b23 100644
--- a/infinite_tracing/test/infinite_tracing/client_test.rb
+++ b/infinite_tracing/test/infinite_tracing/client_test.rb
@@ -21,13 +21,13 @@ def test_streams_multiple_segments
assert_equal total_spans, segments.size
spans.each_with_index do |span, index|
assert_kind_of NewRelic::Agent::InfiniteTracing::Span, span
- assert_equal segments[index].transaction.trace_id, span["trace_id"]
+ assert_equal segments[index].transaction.trace_id, span['trace_id']
end
- refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"])
+ refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped'])
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 5},
- "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 5}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 5},
+ 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 5}
})
end
end
@@ -49,15 +49,15 @@ def test_streams_across_reconnects
assert_equal total_spans, segments.size
assert_equal total_spans, spans.size
- span_ids = spans.map { |s| s["trace_id"] }.sort
+ span_ids = spans.map { |s| s['trace_id'] }.sort
segment_ids = segments.map { |s| s.transaction.trace_id }.sort
assert_equal segment_ids, span_ids
- refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"])
+ refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped'])
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 5},
- "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 5}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 5},
+ 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 5}
})
end
end
@@ -89,15 +89,15 @@ def test_handles_server_disconnects
assert_equal total_spans, segments.size
assert_equal total_spans, spans.size
- span_ids = spans.map { |s| s["trace_id"] }.sort
+ span_ids = spans.map { |s| s['trace_id'] }.sort
segment_ids = segments.map { |s| s.transaction.trace_id }.sort
assert_equal segment_ids, span_ids
- refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"])
+ refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped'])
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 5},
- "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 5}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 5},
+ 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 5}
})
end
end
@@ -113,11 +113,11 @@ def test_handles_server_error_responses
total_spans = 2
emulate_streaming_with_initial_error(total_spans)
- assert_metrics_recorded "Supportability/InfiniteTracing/Span/Sent"
- assert_metrics_recorded "Supportability/InfiniteTracing/Span/Response/Error"
+ assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Sent'
+ assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Response/Error'
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans},
- "Supportability/InfiniteTracing/Span/gRPC/PERMISSION_DENIED" => {:call_count => 1}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans},
+ 'Supportability/InfiniteTracing/Span/gRPC/PERMISSION_DENIED' => {:call_count => 1}
})
end
end
@@ -133,19 +133,19 @@ def test_handles_suspended_state
total_spans = 5
emulate_streaming_segments(total_spans) do |client, segments|
if segments.size == 3
- simulate_server_response_shutdown(GRPC::Unimplemented.new("i dont exist"))
+ simulate_server_response_shutdown(GRPC::Unimplemented.new('i dont exist'))
else
simulate_server_response
end
end
- assert_metrics_recorded "Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED"
- assert_metrics_recorded "Supportability/InfiniteTracing/Span/Sent"
- assert_metrics_recorded "Supportability/InfiniteTracing/Span/Response/Error"
+ assert_metrics_recorded 'Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED'
+ assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Sent'
+ assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Response/Error'
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans},
- "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 3},
- "Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED" => {:call_count => 1}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans},
+ 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 3},
+ 'Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED' => {:call_count => 1}
})
end
end
@@ -214,10 +214,10 @@ def test_streams_multiple_batches
end
end
- refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"])
+ refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped'])
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 5},
- "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 5}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 5},
+ 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 5}
})
end
end
diff --git a/infinite_tracing/test/infinite_tracing/config_test.rb b/infinite_tracing/test/infinite_tracing/config_test.rb
index 8cdf8d4550..ee6b4409d4 100644
--- a/infinite_tracing/test/infinite_tracing/config_test.rb
+++ b/infinite_tracing/test/infinite_tracing/config_test.rb
@@ -35,7 +35,7 @@ def test_trace_observer_host_normalizes
]
hostnames.each do |hostname|
with_config(:'infinite_tracing.trace_observer.host' => hostname) do
- assert_equal "example.com", Config.trace_observer_host
+ assert_equal 'example.com', Config.trace_observer_host
end
end
end
diff --git a/infinite_tracing/test/infinite_tracing/connection_test.rb b/infinite_tracing/test/infinite_tracing/connection_test.rb
index 5986c61b9f..248abb16aa 100644
--- a/infinite_tracing/test/infinite_tracing/connection_test.rb
+++ b/infinite_tracing/test/infinite_tracing/connection_test.rb
@@ -20,8 +20,8 @@ def test_connection_initialized_before_connecting
simulator.join # ensure our simulation happens!
metadata = connection.send(:metadata)
- assert_equal "swiss_cheese", metadata["license_key"]
- assert_equal "fiddlesticks", metadata["agent_run_token"]
+ assert_equal 'swiss_cheese', metadata['license_key']
+ assert_equal 'fiddlesticks', metadata['agent_run_token']
end
end
end
@@ -37,8 +37,8 @@ def test_connection_initialized_after_connecting
connection = Connection.instance # instantiate after simulated connection
metadata = connection.send(:metadata)
- assert_equal "swiss_cheese", metadata["license_key"]
- assert_equal "fiddlesticks", metadata["agent_run_token"]
+ assert_equal 'swiss_cheese', metadata['license_key']
+ assert_equal 'fiddlesticks', metadata['agent_run_token']
end
end
end
@@ -54,8 +54,8 @@ def test_connection_initialized_after_connecting_and_waiting
connection = Connection.instance
metadata = connection.send(:metadata)
- assert_equal "swiss_cheese", metadata["license_key"]
- assert_equal "fiddlesticks", metadata["agent_run_token"]
+ assert_equal 'swiss_cheese', metadata['license_key']
+ assert_equal 'fiddlesticks', metadata['agent_run_token']
end
end
end
@@ -71,15 +71,15 @@ def test_connection_reconnects
simulator.join
metadata = connection.send(:metadata)
- assert_equal "swiss_cheese", metadata["license_key"]
- assert_equal "fiddlesticks", metadata["agent_run_token"]
+ assert_equal 'swiss_cheese', metadata['license_key']
+ assert_equal 'fiddlesticks', metadata['agent_run_token']
simulate_reconnect_to_collector(reconnect_config)
metadata = connection.send(:metadata)
- assert_equal "swiss_cheese", metadata["license_key"]
- assert_equal "shazbat", metadata["agent_run_token"]
+ assert_equal 'swiss_cheese', metadata['license_key']
+ assert_equal 'shazbat', metadata['agent_run_token']
end
end
end
@@ -106,17 +106,17 @@ def test_handling_unimplemented_server_response
spans, segments, active_client = emulate_streaming_to_unimplemented(total_spans)
assert_kind_of SuspendedStreamingBuffer, active_client.buffer
- assert_predicate active_client, :suspended?, "expected client to be suspended."
+ assert_predicate active_client, :suspended?, 'expected client to be suspended.'
assert_equal total_spans, segments.size
assert_equal 0, spans.size
- assert_metrics_recorded "Supportability/InfiniteTracing/Span/Sent"
- assert_metrics_recorded "Supportability/InfiniteTracing/Span/Response/Error"
+ assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Sent'
+ assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Response/Error'
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans},
- "Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED" => {:call_count => 1}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans},
+ 'Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED' => {:call_count => 1}
})
end
end
@@ -131,17 +131,17 @@ def test_handling_failed_precondition_server_response
spans, segments, active_client = emulate_streaming_to_failed_precondition(total_spans)
refute_kind_of SuspendedStreamingBuffer, active_client.buffer
- refute active_client.suspended?, "expected client to not be suspended."
+ refute active_client.suspended?, 'expected client to not be suspended.'
assert_equal total_spans, segments.size
assert_equal 0, spans.size
- assert_metrics_recorded "Supportability/InfiniteTracing/Span/Sent"
- assert_metrics_recorded "Supportability/InfiniteTracing/Span/Response/Error"
+ assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Sent'
+ assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Response/Error'
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans},
- "Supportability/InfiniteTracing/Span/gRPC/FAILED_PRECONDITION" => {:call_count => 5}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans},
+ 'Supportability/InfiniteTracing/Span/gRPC/FAILED_PRECONDITION' => {:call_count => 5}
})
end
end
@@ -151,16 +151,16 @@ def test_handling_ok_and_close_server_response
with_config('infinite_tracing.batching': false) do
with_detailed_trace do
total_spans = 5
- expects_logging(:debug, all_of(includes("closed the stream"), includes("OK response.")), anything)
+ expects_logging(:debug, all_of(includes('closed the stream'), includes('OK response.')), anything)
spans, segments = emulate_streaming_with_ok_close_response(total_spans)
assert_equal total_spans, segments.size
- assert_equal total_spans, spans.size, "spans got dropped/discarded?"
+ assert_equal total_spans, spans.size, 'spans got dropped/discarded?'
- refute_metrics_recorded "Supportability/InfiniteTracing/Span/Response/Error"
+ refute_metrics_recorded 'Supportability/InfiniteTracing/Span/Response/Error'
- assert_metrics_recorded("Supportability/InfiniteTracing/Span/Sent")
+ assert_metrics_recorded('Supportability/InfiniteTracing/Span/Sent')
end
end
end
@@ -188,14 +188,14 @@ def test_reconnection_backoff
def test_metadata_includes_request_headers_map
with_serial_lock do
with_config(localhost_config) do
- NewRelic::Agent.agent.service.instance_variable_set(:@request_headers_map, {"NR-UtilizationMetadata" => "test_metadata"})
+ NewRelic::Agent.agent.service.instance_variable_set(:@request_headers_map, {'NR-UtilizationMetadata' => 'test_metadata'})
connection = Connection.instance # instantiate before simulation
simulate_connect_to_collector(fiddlesticks_config, 0.01) do |simulator|
simulator.join # ensure our simulation happens!
metadata = connection.send(:metadata)
- assert_equal "test_metadata", metadata["nr-utilizationmetadata"]
+ assert_equal 'test_metadata', metadata['nr-utilizationmetadata']
end
end
end
diff --git a/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb b/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb
index b1e1a6cd26..08479442c5 100644
--- a/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb
+++ b/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb
@@ -33,7 +33,7 @@ def test_processes_multiple_items_and_stops
end
def test_processes_error_on_queue
- error_object = RuntimeError.new("oops")
+ error_object = RuntimeError.new('oops')
queue = EnumeratorQueue.new.preload(error_object)
handler = build_handler(queue)
@@ -55,7 +55,7 @@ def test_processes_nil_on_queue
class TestClient
def handle_error(error)
- NewRelic::Agent.record_metric("Supportability/InfiniteTracing/Span/Response/Error", 0.0)
+ NewRelic::Agent.record_metric('Supportability/InfiniteTracing/Span/Response/Error', 0.0)
end
end
diff --git a/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb b/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb
index 5aea73e226..1e263a3489 100644
--- a/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb
+++ b/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb
@@ -23,10 +23,10 @@ def test_streams_single_segment
buffer, _segments = stream_segments(total_spans)
consume_spans(buffer)
- refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"])
+ refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped'])
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 1},
- "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 1}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 1},
+ 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 1}
})
end
end
@@ -43,10 +43,10 @@ def test_streams_single_segment_in_threads
buffer.flush_queue
consumer.join
- refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"])
+ refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped'])
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 1},
- "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 1}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 1},
+ 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 1}
})
assert_watched_threads_finished buffer
end
@@ -62,13 +62,13 @@ def test_streams_multiple_segments
assert_equal total_spans, spans.size
spans.each_with_index do |span, index|
assert_kind_of NewRelic::Agent::InfiniteTracing::Span, span
- assert_equal segments[index].transaction.trace_id, span["trace_id"]
+ assert_equal segments[index].transaction.trace_id, span['trace_id']
end
- refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"])
+ refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped'])
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans},
- "Supportability/InfiniteTracing/Span/Sent" => {:call_count => total_spans}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans},
+ 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => total_spans}
})
assert_watched_threads_finished buffer
end
@@ -122,13 +122,13 @@ def test_streams_multiple_segments_in_threads
assert_equal total_spans, spans.size
spans.each_with_index do |span, index|
assert_kind_of NewRelic::Agent::InfiniteTracing::Span, span
- assert_equal segments[index].transaction.trace_id, span["trace_id"]
+ assert_equal segments[index].transaction.trace_id, span['trace_id']
end
- refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"])
+ refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped'])
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans},
- "Supportability/InfiniteTracing/Span/Sent" => {:call_count => total_spans}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans},
+ 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => total_spans}
})
assert_watched_threads_finished buffer
end
@@ -146,13 +146,13 @@ def test_drops_queue_when_max_reached
spans = consume_spans(buffer)
assert_equal 1, spans.size
- assert_equal segments[-1].transaction.trace_id, spans[0]["trace_id"]
- assert_equal segments[-1].transaction.trace_id, spans[0]["intrinsics"]["traceId"].string_value
+ assert_equal segments[-1].transaction.trace_id, spans[0]['trace_id']
+ assert_equal segments[-1].transaction.trace_id, spans[0]['intrinsics']['traceId'].string_value
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 9},
- "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 1},
- "Supportability/InfiniteTracing/Span/AgentQueueDumped" => {:call_count => 2}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 9},
+ 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 1},
+ 'Supportability/InfiniteTracing/Span/AgentQueueDumped' => {:call_count => 2}
})
assert_watched_threads_finished buffer
end
@@ -184,14 +184,14 @@ def test_can_close_an_empty_buffer
buffer.flush_queue
consumer.join
- assert emptied, "spans streamed reached total but buffer not empty!"
- assert closed, "failed to close the buffer"
+ assert emptied, 'spans streamed reached total but buffer not empty!'
+ assert closed, 'failed to close the buffer'
assert_equal total_spans, segments.size
assert_equal total_spans, spans.size
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans},
- "Supportability/InfiniteTracing/Span/Sent" => {:call_count => total_spans}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans},
+ 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => total_spans}
})
assert_watched_threads_finished buffer
end
diff --git a/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb b/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb
index 9329b397c7..c2dd20ec84 100644
--- a/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb
+++ b/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb
@@ -26,15 +26,15 @@ def test_streams_multiple_segments
assert_equal 0, spans.size
spans.each_with_index do |span, index|
assert_kind_of NewRelic::Agent::InfiniteTracing::Span, span
- assert_equal segments[index].transaction.trace_id, span["trace_id"]
+ assert_equal segments[index].transaction.trace_id, span['trace_id']
end
refute_metrics_recorded([
- "Supportability/InfiniteTracing/Span/AgentQueueDumped",
- "Supportability/InfiniteTracing/Span/Sent"
+ 'Supportability/InfiniteTracing/Span/AgentQueueDumped',
+ 'Supportability/InfiniteTracing/Span/Sent'
])
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans}
})
assert_watched_threads_finished buffer
end
@@ -66,17 +66,17 @@ def test_can_close_an_empty_buffer
buffer.flush_queue
consumer.join
- assert emptied, "spans streamed reached total but buffer not empty!"
- assert closed, "failed to close the buffer"
+ assert emptied, 'spans streamed reached total but buffer not empty!'
+ assert closed, 'failed to close the buffer'
assert_equal total_spans, segments.size
assert_equal 0, spans.size
refute_metrics_recorded([
- "Supportability/InfiniteTracing/Span/AgentQueueDumped",
- "Supportability/InfiniteTracing/Span/Sent"
+ 'Supportability/InfiniteTracing/Span/AgentQueueDumped',
+ 'Supportability/InfiniteTracing/Span/Sent'
])
assert_metrics_recorded({
- "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans}
+ 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans}
})
assert_watched_threads_finished buffer
end
diff --git a/infinite_tracing/test/infinite_tracing/transformer_test.rb b/infinite_tracing/test/infinite_tracing/transformer_test.rb
index d9a4fa7f86..a7d449ca7b 100644
--- a/infinite_tracing/test/infinite_tracing/transformer_test.rb
+++ b/infinite_tracing/test/infinite_tracing/transformer_test.rb
@@ -12,36 +12,36 @@ def test_transforms_single_span_event
span_event = Transformer.transform(span_event_fixture(:single))
assert_kind_of Hash, span_event
- assert_equal "cb4925eee573c1f9c786fdb2b296459b", span_event["trace_id"]
- span_event["intrinsics"].each do |key, value|
+ assert_equal 'cb4925eee573c1f9c786fdb2b296459b', span_event['trace_id']
+ span_event['intrinsics'].each do |key, value|
assert_kind_of String, key
assert_kind_of AttributeValue, value
end
- assert_empty span_event["user_attributes"]
- assert_empty span_event["agent_attributes"]
+ assert_empty span_event['user_attributes']
+ assert_empty span_event['agent_attributes']
end
def test_transforms_single_full_span_event
span_event = Transformer.transform(span_event_fixture(:single_full_attributes))
assert_kind_of Hash, span_event
- assert_equal "cb4925eee573c1f9c786fdb2b296459b", span_event["trace_id"]
+ assert_equal 'cb4925eee573c1f9c786fdb2b296459b', span_event['trace_id']
- span_event["intrinsics"].each do |key, value|
+ span_event['intrinsics'].each do |key, value|
assert_kind_of String, key
assert_kind_of AttributeValue, value
end
- refute_empty span_event["user_attributes"]
- refute_empty span_event["agent_attributes"]
+ refute_empty span_event['user_attributes']
+ refute_empty span_event['agent_attributes']
- span_event["user_attributes"].each do |key, value|
+ span_event['user_attributes'].each do |key, value|
assert_kind_of String, key
assert_kind_of AttributeValue, value
end
- span_event["agent_attributes"].each do |key, value|
+ span_event['agent_attributes'].each do |key, value|
assert_kind_of String, key
assert_kind_of AttributeValue, value
end
diff --git a/infinite_tracing/test/infinite_tracing/worker_test.rb b/infinite_tracing/test/infinite_tracing/worker_test.rb
index 2167ab2b81..acd124383f 100644
--- a/infinite_tracing/test/infinite_tracing/worker_test.rb
+++ b/infinite_tracing/test/infinite_tracing/worker_test.rb
@@ -11,46 +11,46 @@ def teardown
end
def test_processes_simple_task
- worker = Worker.new("simple") do
- NewRelic::Agent.record_metric("Supportability/InfiniteTracing/Worker", 0.0)
+ worker = Worker.new('simple') do
+ NewRelic::Agent.record_metric('Supportability/InfiniteTracing/Worker', 0.0)
end
- assert_equal "run", worker.status
+ assert_equal 'run', worker.status
worker.join
- assert_equal "idle", worker.status
+ assert_equal 'idle', worker.status
worker.stop
- assert_equal "stopped", worker.status
+ assert_equal 'stopped', worker.status
- assert_equal "simple", worker.name
- assert_metrics_recorded "Supportability/InfiniteTracing/Worker"
+ assert_equal 'simple', worker.name
+ assert_metrics_recorded 'Supportability/InfiniteTracing/Worker'
end
def test_worker_uses_agentthread
NewRelic::Agent::Threading::AgentThread.expects(:create).returns(Thread.new {})
- worker = Worker.new("simple") {}
+ worker = Worker.new('simple') {}
worker.join
end
def test_worker_handles_errors
- worker = Worker.new("error") do
- NewRelic::Agent.record_metric("Supportability/InfiniteTracing/Worker", 0.0)
- raise "Oops!"
- NewRelic::Agent.record_metric("Supportability/InfiniteTracing/Error", 0.0)
+ worker = Worker.new('error') do
+ NewRelic::Agent.record_metric('Supportability/InfiniteTracing/Worker', 0.0)
+ raise 'Oops!'
+ NewRelic::Agent.record_metric('Supportability/InfiniteTracing/Error', 0.0)
end
begin
worker.join
rescue => err
- assert_equal "Oops!", err.message
+ assert_equal 'Oops!', err.message
assert worker.error
end
- assert_equal "error", worker.name
- assert_equal "error", worker.status
- assert_metrics_recorded "Supportability/InfiniteTracing/Worker"
- refute_metrics_recorded "Supportability/InfiniteTracing/Error"
+ assert_equal 'error', worker.name
+ assert_equal 'error', worker.status
+ assert_metrics_recorded 'Supportability/InfiniteTracing/Worker'
+ refute_metrics_recorded 'Supportability/InfiniteTracing/Error'
end
end
end
diff --git a/infinite_tracing/test/support/fake_trace_observer_helpers.rb b/infinite_tracing/test/support/fake_trace_observer_helpers.rb
index 791ad16c87..0aee1c9461 100644
--- a/infinite_tracing/test/support/fake_trace_observer_helpers.rb
+++ b/infinite_tracing/test/support/fake_trace_observer_helpers.rb
@@ -52,7 +52,7 @@ def assert_only_one_subscription_notifier
end
def teardown
- @mock_thread.kill if @mock_thread
+ @mock_thread&.kill
@mock_thread = nil
@server_response_enum = nil
reset_buffers_and_caches
@@ -81,8 +81,8 @@ def localhost_config
{
:'distributed_tracing.enabled' => true,
:'span_events.enabled' => true,
- :'infinite_tracing.trace_observer.host' => "localhost:80",
- :'license_key' => "swiss_cheese"
+ :'infinite_tracing.trace_observer.host' => 'localhost:80',
+ :'license_key' => 'swiss_cheese'
}
end
@@ -90,9 +90,9 @@ def fake_server_config
{
:'distributed_tracing.enabled' => true,
:'span_events.enabled' => true,
- :'infinite_tracing.trace_observer.host' => "localhost",
+ :'infinite_tracing.trace_observer.host' => 'localhost',
:'infinite_tracing.trace_observer.port' => FAKE_SERVER_PORT,
- :'license_key' => "swiss_cheese"
+ :'license_key' => 'swiss_cheese'
}
end
@@ -170,7 +170,7 @@ def emulate_streaming_with_tracer(tracer_class, count, max_buffer_size, &block)
end
end
ensure
- client.stop unless client.nil?
+ client&.stop
end
# when the server responds with an error that should stop the server
@@ -215,7 +215,7 @@ def create_grpc_mock(simulate_broken_server: false, expect_mock: true, expect_ba
end
def join_grpc_mock
- @mock_thread.join if @mock_thread
+ @mock_thread&.join
end
# Simulates a Messages seen response from the mock grpc server
@@ -265,7 +265,7 @@ def emulate_streaming_with_initial_error(count, max_buffer_size = 100_000, &bloc
segments = emulate_streaming_with_tracer(nil, count, max_buffer_size) do |client, current_segments|
if first
# raise error only first time
- simulate_server_response_shutdown(GRPC::PermissionDenied.new(details = "denied"))
+ simulate_server_response_shutdown(GRPC::PermissionDenied.new(details = 'denied'))
first = false
else
simulate_server_response
diff --git a/infinite_tracing/test/support/fixtures.rb b/infinite_tracing/test/support/fixtures.rb
index 472b4e43f4..16ff5cc882 100644
--- a/infinite_tracing/test/support/fixtures.rb
+++ b/infinite_tracing/test/support/fixtures.rb
@@ -9,7 +9,7 @@ def fixtures_path
end
def span_event_fixture(fixture_name)
- fixture_filename = File.join(fixtures_path, "span_events", "#{fixture_name}.yml")
+ fixture_filename = File.join(fixtures_path, 'span_events', "#{fixture_name}.yml")
assert_path_exists(fixture_filename, "Missing Span Event Fixture: #{fixture_name}. Looked for #{fixture_filename}")
if YAML.respond_to?(:unsafe_load)
diff --git a/init.rb b/init.rb
index 2711b13570..9c5ac9f02a 100644
--- a/init.rb
+++ b/init.rb
@@ -26,5 +26,5 @@
NewRelic::Control.instance.init_plugin(:config => current_config)
rescue => e
- NewRelic::Agent.logger.error("Error initializing New Relic plugin. Agent is disabled.", e)
+ NewRelic::Agent.logger.error('Error initializing New Relic plugin. Agent is disabled.', e)
end
diff --git a/lib/new_relic/agent.rb b/lib/new_relic/agent.rb
index a729889c6c..3449499dd1 100644
--- a/lib/new_relic/agent.rb
+++ b/lib/new_relic/agent.rb
@@ -105,7 +105,10 @@ class SerializationError < StandardError; end
# placeholder name used when we cannot determine a transaction's name
UNKNOWN_METRIC = '(unknown)'.freeze
+ attr_reader :error_group_callback
+
@agent = nil
+ @error_group_callback = nil
@logger = nil
@tracer_lock = Mutex.new
@tracer_queue = []
@@ -210,6 +213,8 @@ def record_metric_once(metric_name, value = 0.0)
record_metric(metric_name, value)
end
+ SUPPORTABILITY_INCREMENT_METRIC = 'Supportability/API/increment_metric'.freeze
+
# Increment a simple counter metric.
#
# +metric_name+ should follow a slash separated path convention. Application
@@ -218,9 +223,7 @@ def record_metric_once(metric_name, value = 0.0)
# This method is safe to use from any thread.
#
# @api public
-
- SUPPORTABILITY_INCREMENT_METRIC = 'Supportability/API/increment_metric'.freeze
-
+ #
def increment_metric(metric_name, amount = 1) # THREAD_LOCAL_ACCESS
return unless agent
@@ -293,6 +296,47 @@ def notice_error(exception, options = {})
nil # don't return a noticed error data structure. it can only hurt.
end
+ # Set a callback proc for determining an error's error group name
+ #
+ # @param [Proc] the callback proc
+ #
+ # Typically this method should be called only once to set a callback for
+ # use with all noticed errors. If it is called multiple times, each new
+ # callback given will replace the old one.
+ #
+ # The proc will be called with a single hash as its input argument and is
+ # expected to return a string representing the desired error group.
+ #
+ # see https://docs.newrelic.com/docs/errors-inbox/errors-inbox/#groups
+ #
+ # The hash passed to the customer defined callback proc has the following
+ # keys:
+ #
+ # :error => The Ruby error class instance, likely inheriting from
+ # StandardError. Call `#class`, `#message`, and `#backtrace` on
+ # the error object to retrieve the error's class, message, and
+ # backtrace.
+ # :customAttributes => Any customer defined custom attributes that have been
+ # associated with the current transaction.
+ # :'request.uri' => The current request URI if available
+ # :'http.statusCode' => The HTTP status code (200, 404, etc.) if available
+ # :'http.method' => The HTTP method (GET, PUT, etc.) if available
+ # :'error.expected' => Whether (true) or not (false) the error was expected
+ # :options => The options hash passed to `NewRelic::Agent.notice_error`
+ #
+ # @api public
+ #
+ def set_error_group_callback(callback_proc)
+ unless callback_proc.is_a?(Proc)
+ NewRelic::Agent.logger.error("#{self}.#{__method__}: expected an argument of type Proc, " \
+ "got #{callback_proc.class}")
+ return
+ end
+
+ record_api_supportability_metric(:set_error_group_callback)
+ @error_group_callback = callback_proc
+ end
+
# @!endgroup
# @!group Recording custom Insights events
@@ -353,7 +397,7 @@ def record_custom_event(event_type, event_attrs)
# @api public
#
def manual_start(options = {})
- raise "Options must be a hash" unless Hash === options
+ raise 'Options must be a hash' unless Hash === options
NewRelic::Control.instance.init_plugin({:agent_enabled => true, :sync_startup => true}.merge(options))
record_api_supportability_metric(:manual_start)
@@ -386,7 +430,8 @@ def manual_start(options = {})
#
def after_fork(options = {})
record_api_supportability_metric(:after_fork)
- agent.after_fork(options) if agent
+ # the following line needs else branch coverage
+ agent.after_fork(options) if agent # rubocop:disable Style/SafeNavigation
end
# Shutdown the agent. Call this before exiting. Sends any queued data
@@ -398,7 +443,7 @@ def after_fork(options = {})
#
def shutdown(options = {})
record_api_supportability_metric(:shutdown)
- agent.shutdown if agent
+ agent&.shutdown
end
# Clear out any data the agent has buffered but has not yet transmitted
@@ -406,7 +451,8 @@ def shutdown(options = {})
#
# @api public
def drop_buffered_data
- agent.drop_buffered_data if agent
+ # the following line needs else branch coverage
+ agent.drop_buffered_data if agent # rubocop:disable Style/SafeNavigation
record_api_supportability_metric(:drop_buffered_data)
end
@@ -465,8 +511,7 @@ def set_sql_obfuscator(type = :replace, &block)
#
def ignore_transaction
record_api_supportability_metric(:ignore_transaction)
- txn = NewRelic::Agent::Transaction.tl_current
- txn.ignore! if txn
+ NewRelic::Agent::Transaction.tl_current&.ignore!
end
# This method disables the recording of Apdex metrics in the current
@@ -476,8 +521,7 @@ def ignore_transaction
#
def ignore_apdex
record_api_supportability_metric(:ignore_apdex)
- txn = NewRelic::Agent::Transaction.tl_current
- txn.ignore_apdex! if txn
+ NewRelic::Agent::Transaction.tl_current&.ignore_apdex!
end
# This method disables browser monitoring javascript injection in the
@@ -487,8 +531,7 @@ def ignore_apdex
#
def ignore_enduser
record_api_supportability_metric(:ignore_enduser)
- txn = NewRelic::Agent::Transaction.tl_current
- txn.ignore_enduser! if txn
+ NewRelic::Agent::Transaction.tl_current&.ignore_enduser!
end
# Yield to the block without collecting any metrics or traces in
@@ -564,8 +607,7 @@ def add_custom_attributes(params) # THREAD_LOCAL_ACCESS
record_api_supportability_metric(:add_custom_attributes)
if params.is_a?(Hash)
- txn = Transaction.tl_current
- txn.add_custom_attributes(params) if txn
+ Transaction.tl_current&.add_custom_attributes(params)
segment = ::NewRelic::Agent::Tracer.current_segment
if segment
@@ -607,6 +649,26 @@ def add_custom_span_attributes(params)
end
end
+ # Set the user id for the current transaction. When present, this value will be included in the agent attributes for transaction and error events as 'enduser.id'.
+ #
+ # @param [String] user_id The user id to add to the current transaction attributes
+ #
+ # @api public
+ def set_user_id(user_id)
+ record_api_supportability_metric(:set_user_id)
+
+ if user_id.nil? || user_id.empty?
+ ::NewRelic::Agent.logger.warn('NewRelic::Agent.set_user_id called with a nil or empty user id.')
+ return
+ end
+
+ default_destinations = NewRelic::Agent::AttributeFilter::DST_TRANSACTION_TRACER |
+ NewRelic::Agent::AttributeFilter::DST_TRANSACTION_EVENTS |
+ NewRelic::Agent::AttributeFilter::DST_ERROR_COLLECTOR
+
+ NewRelic::Agent::Transaction.add_agent_attribute(:'enduser.id', user_id, default_destinations)
+ end
+
# @!endgroup
# @!group Transaction naming
@@ -686,7 +748,7 @@ def subscribe(event_type, &handler)
def notify(event_type, *args)
agent.events.notify(event_type, *args)
rescue
- NewRelic::Agent.logger.debug("Ignoring exception during %p event notification" % [event_type])
+ NewRelic::Agent.logger.debug('Ignoring exception during %p event notification' % [event_type])
end
# @!group Trace and Entity metadata
diff --git a/lib/new_relic/agent/agent.rb b/lib/new_relic/agent/agent.rb
index a004ba147a..0e5b947666 100644
--- a/lib/new_relic/agent/agent.rb
+++ b/lib/new_relic/agent/agent.rb
@@ -142,20 +142,16 @@ module InstanceMethods
# the transaction sampler that handles recording transactions
attr_reader :transaction_sampler
attr_reader :sql_sampler
- # manages agent commands we receive from the collector, and the handlers
- attr_reader :agent_command_router
# error collector is a simple collection of recorded errors
attr_reader :error_collector
- attr_reader :harvest_samplers
# whether we should record raw, obfuscated, or no sql
attr_reader :record_sql
# builder for JS agent scripts to inject
attr_reader :javascript_instrumentor
# cross application tracing ids and encoding
attr_reader :cross_process_id
- attr_reader :cross_app_encoding_bytes
# service for communicating with collector
- attr_accessor :service
+ attr_reader :service
# Global events dispatcher. This will provides our primary mechanism
# for agent-wide events, such as finishing configuration, error notification
# and request before/after from Rack.
@@ -168,8 +164,6 @@ module InstanceMethods
# collector on connect. The former are applied during txns,
# the latter during harvest.
attr_accessor :transaction_rules
- # Responsible for restarting the harvest thread
- attr_reader :harvester
# GC::Profiler.total_time is not monotonic so we wrap it.
attr_reader :monotonic_gc_profiler
attr_reader :custom_event_aggregator
@@ -178,7 +172,6 @@ module InstanceMethods
attr_reader :transaction_event_recorder
attr_reader :attribute_filter
attr_reader :adaptive_sampler
- attr_reader :environment_report
def transaction_event_aggregator
@transaction_event_recorder.transaction_event_aggregator
@@ -262,8 +255,8 @@ def trap_signals_for_litespeed
# if litespeed, then ignore all future SIGUSR1 - it's
# litespeed trying to shut us down
if Agent.config[:dispatcher] == :litespeed
- Signal.trap("SIGUSR1", "IGNORE")
- Signal.trap("SIGTERM", "IGNORE")
+ Signal.trap('SIGUSR1', 'IGNORE')
+ Signal.trap('SIGTERM', 'IGNORE')
end
end
@@ -355,12 +348,6 @@ def merge_data_for_endpoint(endpoint, data)
end
public :merge_data_for_endpoint
-
- # Delegates to the control class to determine the root
- # directory of this project
- def determine_home_directory
- control.root
- end
end
extend ClassMethods
diff --git a/lib/new_relic/agent/agent_helpers/connect.rb b/lib/new_relic/agent/agent_helpers/connect.rb
index e4380e0de9..fe0c8c18d1 100644
--- a/lib/new_relic/agent/agent_helpers/connect.rb
+++ b/lib/new_relic/agent/agent_helpers/connect.rb
@@ -64,7 +64,7 @@ def log_error(error)
def handle_license_error(error)
::NewRelic::Agent.logger.error( \
error.message, \
- "Visit NewRelic.com to obtain a valid license key, or to upgrade your account."
+ 'Visit NewRelic.com to obtain a valid license key, or to upgrade your account.'
)
disconnect
end
@@ -115,7 +115,7 @@ def log_connection(config_data)
::NewRelic::Agent.logger.debug("Connected to NewRelic Service at #{@service.collector.name}")
::NewRelic::Agent.logger.debug("Agent Run = #{@service.agent_id}.")
::NewRelic::Agent.logger.debug("Connection data = #{config_data.inspect}")
- if config_data['messages'] && config_data['messages'].any?
+ if config_data['messages']&.any?
log_collector_messages(config_data['messages'])
end
end
@@ -126,11 +126,6 @@ def log_collector_messages(messages)
end
end
- # apdex_f is always 4 times the apdex_t
- def apdex_f
- (Agent.config[:apdex_t] * 4).to_f
- end
-
class WaitOnConnectTimeout < StandardError
end
@@ -149,7 +144,7 @@ def wait_on_connect(timeout)
return if connected?
@waited_on_connect = true
- NewRelic::Agent.logger.debug("Waiting on connect to complete.")
+ NewRelic::Agent.logger.debug('Waiting on connect to complete.')
@wait_on_connect_mutex.synchronize do
@wait_on_connect_condition.wait(@wait_on_connect_mutex, timeout)
@@ -203,7 +198,7 @@ def connect(options = {})
rescue StandardError, Timeout::Error, NewRelic::Agent::ServerConnectionException => e
retry if retry_from_error?(e, opts)
rescue Exception => e
- ::NewRelic::Agent.logger.error("Exception of unexpected type during Agent#connect():", e)
+ ::NewRelic::Agent.logger.error('Exception of unexpected type during Agent#connect():', e)
raise
end
diff --git a/lib/new_relic/agent/agent_helpers/harvest.rb b/lib/new_relic/agent/agent_helpers/harvest.rb
index f760a2e4a2..af5596ad21 100644
--- a/lib/new_relic/agent/agent_helpers/harvest.rb
+++ b/lib/new_relic/agent/agent_helpers/harvest.rb
@@ -133,18 +133,18 @@ def check_for_and_handle_agent_commands
rescue ForceRestartException, ForceDisconnectException
raise
rescue UnrecoverableServerException => e
- NewRelic::Agent.logger.warn("get_agent_commands message was rejected by remote service, discarding. " \
- "Error: ", e)
+ NewRelic::Agent.logger.warn('get_agent_commands message was rejected by remote service, discarding. ' \
+ 'Error: ', e)
rescue ServerConnectionException => e
log_remote_unavailable(:get_agent_commands, e)
rescue => e
- NewRelic::Agent.logger.info("Error during check_for_and_handle_agent_commands, will retry later: ", e)
+ NewRelic::Agent.logger.info('Error during check_for_and_handle_agent_commands, will retry later: ', e)
end
end
def log_remote_unavailable(endpoint, e)
NewRelic::Agent.logger.debug("Unable to send #{endpoint} data, will try again later. Error: ", e)
- NewRelic::Agent.record_metric("Supportability/remote_unavailable", 0.0)
+ NewRelic::Agent.record_metric('Supportability/remote_unavailable', 0.0)
NewRelic::Agent.record_metric("Supportability/remote_unavailable/#{endpoint.to_s}", 0.0)
end
end
diff --git a/lib/new_relic/agent/agent_helpers/shutdown.rb b/lib/new_relic/agent/agent_helpers/shutdown.rb
index 868e914177..e6f6017e13 100644
--- a/lib/new_relic/agent/agent_helpers/shutdown.rb
+++ b/lib/new_relic/agent/agent_helpers/shutdown.rb
@@ -11,7 +11,7 @@ module Shutdown
def shutdown
return unless started?
- ::NewRelic::Agent.logger.info("Starting Agent shutdown")
+ ::NewRelic::Agent.logger.info('Starting Agent shutdown')
stop_event_loop
trap_signals_for_litespeed
@@ -48,22 +48,22 @@ def graceful_disconnect
transmit_data_types
shutdown_service
- ::NewRelic::Agent.logger.debug("Graceful disconnect complete")
+ ::NewRelic::Agent.logger.debug('Graceful disconnect complete')
rescue Timeout::Error, StandardError => e
::NewRelic::Agent.logger.debug("Error when disconnecting #{e.class.name}: #{e.message}")
end
else
- ::NewRelic::Agent.logger.debug("Bypassing graceful disconnect - agent not connected")
+ ::NewRelic::Agent.logger.debug('Bypassing graceful disconnect - agent not connected')
end
end
def shutdown_service
if @connected_pid == $$ && !@service.kind_of?(NewRelic::Agent::NewRelicService)
- ::NewRelic::Agent.logger.debug("Sending New Relic service agent run shutdown message")
+ ::NewRelic::Agent.logger.debug('Sending New Relic service agent run shutdown message')
@service.shutdown
else
::NewRelic::Agent.logger.debug("This agent connected from parent process #{@connected_pid}--not sending " \
- "shutdown")
+ 'shutdown')
end
end
end
diff --git a/lib/new_relic/agent/agent_helpers/special_startup.rb b/lib/new_relic/agent/agent_helpers/special_startup.rb
index 9fb2bb0160..08b5d4cf33 100644
--- a/lib/new_relic/agent/agent_helpers/special_startup.rb
+++ b/lib/new_relic/agent/agent_helpers/special_startup.rb
@@ -11,7 +11,7 @@ module SpecialStartup
# before connecting, otherwise the parent process sends useless data
def using_forking_dispatcher?
if [:puma, :passenger, :unicorn].include?(Agent.config[:dispatcher])
- ::NewRelic::Agent.logger.info("Deferring startup of agent reporting thread because " \
+ ::NewRelic::Agent.logger.info('Deferring startup of agent reporting thread because ' \
"#{Agent.config[:dispatcher]} may fork.")
true
else
@@ -65,7 +65,7 @@ def should_install_exit_handler?
def install_exit_handler
return unless should_install_exit_handler?
- NewRelic::Agent.logger.debug("Installing at_exit handler")
+ NewRelic::Agent.logger.debug('Installing at_exit handler')
at_exit { shutdown }
end
end
diff --git a/lib/new_relic/agent/agent_helpers/start_worker_thread.rb b/lib/new_relic/agent/agent_helpers/start_worker_thread.rb
index 1d51923078..d59f0d3229 100644
--- a/lib/new_relic/agent/agent_helpers/start_worker_thread.rb
+++ b/lib/new_relic/agent/agent_helpers/start_worker_thread.rb
@@ -8,23 +8,23 @@ module AgentHelpers
module StartWorkerThread
LOG_ONCE_KEYS_RESET_PERIOD = 60.0
- TRANSACTION_EVENT_DATA = "transaction_event_data".freeze
- CUSTOM_EVENT_DATA = "custom_event_data".freeze
- ERROR_EVENT_DATA = "error_event_data".freeze
- SPAN_EVENT_DATA = "span_event_data".freeze
- LOG_EVENT_DATA = "log_event_data".freeze
+ TRANSACTION_EVENT_DATA = 'transaction_event_data'.freeze
+ CUSTOM_EVENT_DATA = 'custom_event_data'.freeze
+ ERROR_EVENT_DATA = 'error_event_data'.freeze
+ SPAN_EVENT_DATA = 'span_event_data'.freeze
+ LOG_EVENT_DATA = 'log_event_data'.freeze
# Try to launch the worker thread and connect to the server.
#
# See #connect for a description of connection_options.
def start_worker_thread(connection_options = {})
if disable = NewRelic::Agent.config[:disable_harvest_thread]
- NewRelic::Agent.logger.info("Not starting Ruby Agent worker thread because :disable_harvest_thread is " \
+ NewRelic::Agent.logger.info('Not starting Ruby Agent worker thread because :disable_harvest_thread is ' \
"#{disable}")
return
end
- ::NewRelic::Agent.logger.debug("Creating Ruby Agent worker thread.")
+ ::NewRelic::Agent.logger.debug('Creating Ruby Agent worker thread.')
@worker_thread = Threading::AgentThread.create('Worker Loop') do
deferred_work!(connection_options)
end
@@ -42,11 +42,11 @@ def create_event_loop
# The use-case where this typically arises is in cronjob scheduled rake tasks where there's
# also some network stability/latency issues happening.
def stop_event_loop
- @event_loop.stop if @event_loop
+ @event_loop&.stop
# Wait the end of the event loop thread.
if @worker_thread
unless @worker_thread.join(3)
- ::NewRelic::Agent.logger.debug("Event loop thread did not stop within 3 seconds")
+ ::NewRelic::Agent.logger.debug('Event loop thread did not stop within 3 seconds')
end
end
end
@@ -60,36 +60,13 @@ def interval_for(event_type)
end
def create_and_run_event_loop
- data_harvest = :"#{Agent.config[:data_report_period]}_second_harvest"
- event_harvest = :"#{Agent.config[:event_report_period]}_second_harvest"
-
@event_loop = create_event_loop
+ data_harvest = :"#{Agent.config[:data_report_period]}_second_harvest"
@event_loop.on(data_harvest) do
transmit_data
end
-
- @event_loop.on(interval_for(TRANSACTION_EVENT_DATA)) do
- transmit_analytic_event_data
- end
- @event_loop.on(interval_for(CUSTOM_EVENT_DATA)) do
- transmit_custom_event_data
- end
- @event_loop.on(interval_for(ERROR_EVENT_DATA)) do
- transmit_error_event_data
- end
- @event_loop.on(interval_for(SPAN_EVENT_DATA)) do
- transmit_span_event_data
- end
- @event_loop.on(interval_for(LOG_EVENT_DATA)) do
- transmit_log_event_data
- end
-
- @event_loop.on(:reset_log_once_keys) do
- ::NewRelic::Agent.logger.clear_already_logged
- end
- @event_loop.fire_every(Agent.config[:data_report_period], data_harvest)
- @event_loop.fire_every(Agent.config[:event_report_period], event_harvest)
- @event_loop.fire_every(LOG_ONCE_KEYS_RESET_PERIOD, :reset_log_once_keys)
+ establish_interval_transmissions
+ establish_fire_everies(data_harvest)
@event_loop.run
end
@@ -100,7 +77,7 @@ def create_and_run_event_loop
def handle_force_restart(error)
::NewRelic::Agent.logger.debug(error.message)
drop_buffered_data
- @service.force_restart if @service
+ @service&.force_restart
@connect_state = :pending
sleep(30)
end
@@ -109,7 +86,7 @@ def handle_force_restart(error)
# is the worker thread that gathers data and talks to the
# server.
def handle_force_disconnect(error)
- ::NewRelic::Agent.logger.warn("Agent received a ForceDisconnectException from the server, disconnecting. " \
+ ::NewRelic::Agent.logger.warn('Agent received a ForceDisconnectException from the server, disconnecting. ' \
"(#{error.message})")
disconnect
end
@@ -118,7 +95,7 @@ def handle_force_disconnect(error)
# it and disconnecting the agent, since we are now in an
# unknown state.
def handle_other_error(error)
- ::NewRelic::Agent.logger.error("Unhandled error in worker thread, disconnecting.")
+ ::NewRelic::Agent.logger.error('Unhandled error in worker thread, disconnecting.')
# These errors are fatal (that is, they will prevent the agent from
# reporting entirely), so we really want backtraces when they happen
::NewRelic::Agent.logger.log_exception(:error, error)
@@ -156,11 +133,42 @@ def deferred_work!(connection_options)
# never reaches here unless there is a problem or
# the agent is exiting
else
- ::NewRelic::Agent.logger.debug("No connection. Worker thread ending.")
+ ::NewRelic::Agent.logger.debug('No connection. Worker thread ending.')
end
end
end
end
+
+ private
+
+ def establish_interval_transmissions
+ @event_loop.on(interval_for(TRANSACTION_EVENT_DATA)) do
+ transmit_analytic_event_data
+ end
+ @event_loop.on(interval_for(CUSTOM_EVENT_DATA)) do
+ transmit_custom_event_data
+ end
+ @event_loop.on(interval_for(ERROR_EVENT_DATA)) do
+ transmit_error_event_data
+ end
+ @event_loop.on(interval_for(SPAN_EVENT_DATA)) do
+ transmit_span_event_data
+ end
+ @event_loop.on(interval_for(LOG_EVENT_DATA)) do
+ transmit_log_event_data
+ end
+ end
+
+ def establish_fire_everies(data_harvest)
+ @event_loop.on(:reset_log_once_keys) do
+ ::NewRelic::Agent.logger.clear_already_logged
+ end
+
+ event_harvest = :"#{Agent.config[:event_report_period]}_second_harvest"
+ @event_loop.fire_every(Agent.config[:data_report_period], data_harvest)
+ @event_loop.fire_every(Agent.config[:event_report_period], event_harvest)
+ @event_loop.fire_every(LOG_ONCE_KEYS_RESET_PERIOD, :reset_log_once_keys)
+ end
end
end
end
diff --git a/lib/new_relic/agent/agent_helpers/startup.rb b/lib/new_relic/agent/agent_helpers/startup.rb
index b312e7d00f..c71719a95d 100644
--- a/lib/new_relic/agent/agent_helpers/startup.rb
+++ b/lib/new_relic/agent/agent_helpers/startup.rb
@@ -14,7 +14,7 @@ def started?
# Check whether we have already started, which is an error condition
def already_started?
if started?
- ::NewRelic::Agent.logger.error("Agent Started Already!")
+ ::NewRelic::Agent.logger.error('Agent Started Already!')
true
end
end
@@ -87,15 +87,15 @@ def log_dispatcher
end
def log_app_name
- ::NewRelic::Agent.logger.info("Application: #{Agent.config[:app_name].join(", ")}")
+ ::NewRelic::Agent.logger.info("Application: #{Agent.config[:app_name].join(', ')}")
end
def log_ignore_url_regexes
regexes = NewRelic::Agent.config[:'rules.ignore_url_regexes']
unless regexes.empty?
- ::NewRelic::Agent.logger.info("Ignoring URLs that match the following regexes: " \
- "#{regexes.map(&:inspect).join(", ")}.")
+ ::NewRelic::Agent.logger.info('Ignoring URLs that match the following regexes: ' \
+ "#{regexes.map(&:inspect).join(', ')}.")
end
end
@@ -138,10 +138,10 @@ def has_license_key?
if Agent.config[:license_key] && Agent.config[:license_key].length > 0
true
else
- ::NewRelic::Agent.logger.warn("No license key found. " +
- "This often means your newrelic.yml file was not found, or it lacks a section for the running " \
+ ::NewRelic::Agent.logger.warn('No license key found. ' +
+ 'This often means your newrelic.yml file was not found, or it lacks a section for the running ' \
"environment, '#{NewRelic::Control.instance.env}'. You may also want to try linting your newrelic.yml " \
- "to ensure it is valid YML.")
+ 'to ensure it is valid YML.')
false
end
end
@@ -169,21 +169,21 @@ def agent_should_start?
return false if already_started? || disabled?
if defer_for_delayed_job?
- ::NewRelic::Agent.logger.debug("Deferring startup for DelayedJob")
+ ::NewRelic::Agent.logger.debug('Deferring startup for DelayedJob')
return false
end
if defer_for_resque?
- ::NewRelic::Agent.logger.debug("Deferring startup for Resque in case it daemonizes")
+ ::NewRelic::Agent.logger.debug('Deferring startup for Resque in case it daemonizes')
return false
end
unless app_name_configured?
- NewRelic::Agent.logger.error("No application name configured.",
- "The Agent cannot start without at least one. Please check your ",
- "newrelic.yml and ensure that it is valid and has at least one ",
+ NewRelic::Agent.logger.error('No application name configured.',
+ 'The Agent cannot start without at least one. Please check your ',
+ 'newrelic.yml and ensure that it is valid and has at least one ',
"value set for app_name in the #{NewRelic::Control.instance.env} ",
- "environment.")
+ 'environment.')
return false
end
diff --git a/lib/new_relic/agent/agent_helpers/transmit.rb b/lib/new_relic/agent/agent_helpers/transmit.rb
index 6741206c94..5ab441a0f6 100644
--- a/lib/new_relic/agent/agent_helpers/transmit.rb
+++ b/lib/new_relic/agent/agent_helpers/transmit.rb
@@ -6,27 +6,27 @@ module NewRelic
module Agent
module AgentHelpers
module Transmit
- TRANSACTION_EVENT = "TransactionEvent".freeze
+ TRANSACTION_EVENT = 'TransactionEvent'.freeze
def transmit_analytic_event_data
transmit_single_data_type(:harvest_and_send_analytic_event_data, TRANSACTION_EVENT)
end
- CUSTOM_EVENT = "CustomEvent".freeze
+ CUSTOM_EVENT = 'CustomEvent'.freeze
def transmit_custom_event_data
transmit_single_data_type(:harvest_and_send_custom_event_data, CUSTOM_EVENT)
end
- ERROR_EVENT = "ErrorEvent".freeze
+ ERROR_EVENT = 'ErrorEvent'.freeze
def transmit_error_event_data
transmit_single_data_type(:harvest_and_send_error_event_data, ERROR_EVENT)
end
- SPAN_EVENT = "SpanEvent".freeze
+ SPAN_EVENT = 'SpanEvent'.freeze
def transmit_span_event_data
transmit_single_data_type(:harvest_and_send_span_event_data, SPAN_EVENT)
end
- LOG_EVENT = "LogEvent".freeze
+ LOG_EVENT = 'LogEvent'.freeze
def transmit_log_event_data
transmit_single_data_type(:harvest_and_send_log_event_data, LOG_EVENT)
end
@@ -47,7 +47,7 @@ def transmit_single_data_type(harvest_method, supportability_name)
def transmit_data
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
- ::NewRelic::Agent.logger.debug("Sending data to New Relic Service")
+ ::NewRelic::Agent.logger.debug('Sending data to New Relic Service')
@events.notify(:before_harvest)
@service.session do # use http keep-alive
diff --git a/lib/new_relic/agent/agent_logger.rb b/lib/new_relic/agent/agent_logger.rb
index f97e45550a..e5fe2fa1e9 100644
--- a/lib/new_relic/agent/agent_logger.rb
+++ b/lib/new_relic/agent/agent_logger.rb
@@ -13,7 +13,7 @@ module Agent
class AgentLogger
include LogOnce
- def initialize(root = "", override_logger = nil)
+ def initialize(root = '', override_logger = nil)
@already_logged_lock = Mutex.new
clear_already_logged
create_log(root, override_logger)
@@ -53,13 +53,13 @@ def is_startup_logger?
# default behavior of backtraces logged at debug, use one of the methods
# above and pass an Exception as one of the args.
def log_exception(level, e, backtrace_level = level)
- @log.send(level, "%p: %s" % [e.class, e.message])
+ @log.send(level, '%p: %s' % [e.class, e.message])
@log.send(backtrace_level) do
backtrace = backtrace_from_exception(e)
if backtrace
"Debugging backtrace:\n" + backtrace.join("\n ")
else
- "No backtrace available."
+ 'No backtrace available.'
end
end
end
@@ -150,11 +150,11 @@ def set_log_level!
end
LOG_LEVELS = {
- "debug" => ::Logger::DEBUG,
- "info" => ::Logger::INFO,
- "warn" => ::Logger::WARN,
- "error" => ::Logger::ERROR,
- "fatal" => ::Logger::FATAL
+ 'debug' => ::Logger::DEBUG,
+ 'info' => ::Logger::INFO,
+ 'warn' => ::Logger::WARN,
+ 'error' => ::Logger::ERROR,
+ 'fatal' => ::Logger::FATAL
}
def self.log_level_for(level)
@@ -165,7 +165,7 @@ def set_log_format!
@hostname = NewRelic::Agent::Hostname.get
@prefix = wants_stdout? ? '** [NewRelic]' : ''
@log.formatter = proc do |severity, timestamp, progname, msg|
- "#{@prefix}[#{timestamp.strftime("%F %H:%M:%S %z")} #{@hostname} (#{$$})] #{severity} : #{msg}\n"
+ "#{@prefix}[#{timestamp.strftime('%F %H:%M:%S %z')} #{@hostname} (#{$$})] #{severity} : #{msg}\n"
end
end
diff --git a/lib/new_relic/agent/attribute_filter.rb b/lib/new_relic/agent/attribute_filter.rb
index 4a5dcc42d9..bc082daba8 100644
--- a/lib/new_relic/agent/attribute_filter.rb
+++ b/lib/new_relic/agent/attribute_filter.rb
@@ -273,8 +273,8 @@ class AttributeFilterRule
attr_reader :attribute_name, :destinations, :is_include, :wildcard
def initialize(attribute_name, destinations, is_include)
- @attribute_name = attribute_name.sub(/\*$/, "")
- @wildcard = attribute_name.end_with?("*")
+ @attribute_name = attribute_name.sub(/\*$/, '')
+ @wildcard = attribute_name.end_with?('*')
@is_include = is_include
@destinations = is_include ? destinations : ~destinations
end
diff --git a/lib/new_relic/agent/attribute_processing.rb b/lib/new_relic/agent/attribute_processing.rb
index 6f7b033a33..e23a145c9a 100644
--- a/lib/new_relic/agent/attribute_processing.rb
+++ b/lib/new_relic/agent/attribute_processing.rb
@@ -7,8 +7,8 @@ module Agent
module AttributeProcessing
module_function
- EMPTY_HASH_STRING_LITERAL = "{}".freeze
- EMPTY_ARRAY_STRING_LITERAL = "[]".freeze
+ EMPTY_HASH_STRING_LITERAL = '{}'.freeze
+ EMPTY_ARRAY_STRING_LITERAL = '[]'.freeze
def flatten_and_coerce(object, prefix = nil, result = {}, &blk)
if object.is_a?(Hash)
diff --git a/lib/new_relic/agent/audit_logger.rb b/lib/new_relic/agent/audit_logger.rb
index 8290373830..0e63a5cc0b 100644
--- a/lib/new_relic/agent/audit_logger.rb
+++ b/lib/new_relic/agent/audit_logger.rb
@@ -32,9 +32,9 @@ def log_request_headers(uri, headers)
@log.info("REQUEST HEADERS: #{headers}")
rescue StandardError, SystemStackError, SystemCallError => e
- ::NewRelic::Agent.logger.warn("Failed writing request headers to audit log", e)
+ ::NewRelic::Agent.logger.warn('Failed writing request headers to audit log', e)
rescue Exception => e
- ::NewRelic::Agent.logger.warn("Failed writing request headers to audit log with exception. Re-raising in case of interrupt.", e)
+ ::NewRelic::Agent.logger.warn('Failed writing request headers to audit log with exception. Re-raising in case of interrupt.', e)
raise
end
@@ -50,9 +50,9 @@ def log_request(uri, data, marshaller)
@log.info("REQUEST: #{uri}")
@log.info("REQUEST BODY: #{request_body}")
rescue StandardError, SystemStackError, SystemCallError => e
- ::NewRelic::Agent.logger.warn("Failed writing to audit log", e)
+ ::NewRelic::Agent.logger.warn('Failed writing to audit log', e)
rescue Exception => e
- ::NewRelic::Agent.logger.warn("Failed writing to audit log with exception. Re-raising in case of interrupt.", e)
+ ::NewRelic::Agent.logger.warn('Failed writing to audit log with exception. Re-raising in case of interrupt.', e)
raise
end
@@ -64,7 +64,7 @@ def setup_logger
if wants_stdout?
# Using $stdout global for easier reassignment in testing
@log = ::Logger.new($stdout)
- ::NewRelic::Agent.logger.info("Audit log enabled to STDOUT")
+ ::NewRelic::Agent.logger.info('Audit log enabled to STDOUT')
elsif path = ensure_log_path
@log = ::Logger.new(path)
::NewRelic::Agent.logger.info("Audit log enabled at '#{path}'")
diff --git a/lib/new_relic/agent/autostart.rb b/lib/new_relic/agent/autostart.rb
index 57307b42db..12a7ab1a6b 100644
--- a/lib/new_relic/agent/autostart.rb
+++ b/lib/new_relic/agent/autostart.rb
@@ -28,7 +28,7 @@ def agent_should_start?
!in_denylisted_rake_task?
end
- COMMA = ",".freeze
+ COMMA = ','.freeze
def denylisted_constants?
denylisted?(NewRelic::Agent.config[:'autostart.denylisted_constants']) do |name|
diff --git a/lib/new_relic/agent/commands/agent_command.rb b/lib/new_relic/agent/commands/agent_command.rb
index e9c23538b3..9c1a0d0af5 100644
--- a/lib/new_relic/agent/commands/agent_command.rb
+++ b/lib/new_relic/agent/commands/agent_command.rb
@@ -10,8 +10,8 @@ class AgentCommand
def initialize(raw_collector_command)
@id = raw_collector_command[0]
- @name = raw_collector_command[1]["name"]
- @arguments = raw_collector_command[1]["arguments"]
+ @name = raw_collector_command[1]['name']
+ @arguments = raw_collector_command[1]['arguments']
end
end
end
diff --git a/lib/new_relic/agent/commands/agent_command_router.rb b/lib/new_relic/agent/commands/agent_command_router.rb
index 083d9a7cda..cf8a0e3e81 100644
--- a/lib/new_relic/agent/commands/agent_command_router.rb
+++ b/lib/new_relic/agent/commands/agent_command_router.rb
@@ -29,7 +29,8 @@ def initialize(event_listener = nil)
@handlers['start_profiler'] = proc { |cmd| thread_profiler_session.handle_start_command(cmd) }
@handlers['stop_profiler'] = proc { |cmd| thread_profiler_session.handle_stop_command(cmd) }
- if event_listener
+ # the following statement needs else branch coverage
+ if event_listener # rubocop:disable Style/SafeNavigation
event_listener.subscribe(:before_shutdown, &method(:on_before_shutdown))
end
end
@@ -77,10 +78,10 @@ def harvest_from_thread_profiler_session
def log_profiles(profiles)
if profiles.empty?
- ::NewRelic::Agent.logger.debug("No thread profiles with data found to send.")
+ ::NewRelic::Agent.logger.debug('No thread profiles with data found to send.')
else
profile_descriptions = profiles.map { |p| p.to_log_description }
- ::NewRelic::Agent.logger.debug("Sending thread profiles [#{profile_descriptions.join(", ")}]")
+ ::NewRelic::Agent.logger.debug("Sending thread profiles [#{profile_descriptions.join(', ')}]")
end
end
@@ -114,7 +115,7 @@ def invoke_command(agent_command)
end
SUCCESS_RESULT = NewRelic::EMPTY_HASH
- ERROR_KEY = "error"
+ ERROR_KEY = 'error'
def success
SUCCESS_RESULT
diff --git a/lib/new_relic/agent/commands/thread_profiler_session.rb b/lib/new_relic/agent/commands/thread_profiler_session.rb
index 8f65372cc0..e9976e62d5 100644
--- a/lib/new_relic/agent/commands/thread_profiler_session.rb
+++ b/lib/new_relic/agent/commands/thread_profiler_session.rb
@@ -25,12 +25,12 @@ def handle_start_command(agent_command)
end
def handle_stop_command(agent_command)
- report_data = agent_command.arguments.fetch("report_data", true)
+ report_data = agent_command.arguments.fetch('report_data', true)
stop(report_data)
end
def start(agent_command)
- NewRelic::Agent.logger.debug("Starting Thread Profiler.")
+ NewRelic::Agent.logger.debug('Starting Thread Profiler.')
profile = @backtrace_service.subscribe(
NewRelic::Agent::Threading::BacktraceService::ALL_TRANSACTIONS,
agent_command.arguments
@@ -43,7 +43,7 @@ def start(agent_command)
def stop(report_data)
return unless running?
- NewRelic::Agent.logger.debug("Stopping Thread Profiler.")
+ NewRelic::Agent.logger.debug('Stopping Thread Profiler.')
@finished_profile = @backtrace_service.harvest(NewRelic::Agent::Threading::BacktraceService::ALL_TRANSACTIONS)
@backtrace_service.unsubscribe(NewRelic::Agent::Threading::BacktraceService::ALL_TRANSACTIONS)
@finished_profile = nil if !report_data
@@ -51,7 +51,7 @@ def stop(report_data)
def harvest
NewRelic::Agent.logger.debug(
- "Harvesting from Thread Profiler #{@finished_profile.to_log_description unless @finished_profile.nil?}"
+ "Harvesting from Thread Profiler #{@finished_profile&.to_log_description}"
)
profile = @finished_profile
@backtrace_service.profile_agent_code = false
@@ -102,7 +102,7 @@ def raise_thread_profiler_disabled
end
def raise_already_started_error
- msg = "Profile already in progress. Ignoring agent command to start another."
+ msg = 'Profile already in progress. Ignoring agent command to start another.'
raise_command_error(msg)
end
end
diff --git a/lib/new_relic/agent/configuration/default_source.rb b/lib/new_relic/agent/configuration/default_source.rb
index 1b0c6a5666..85a862f06a 100644
--- a/lib/new_relic/agent/configuration/default_source.rb
+++ b/lib/new_relic/agent/configuration/default_source.rb
@@ -29,11 +29,11 @@ def self.value_of(key)
def self.instrumentation_value_of(disable_key, prepend_key = nil)
proc do
if NewRelic::Agent.config[disable_key]
- "disabled"
+ 'disabled'
elsif prepend_key && !NewRelic::Agent.config[prepend_key]
- "chain"
+ 'chain'
else
- "auto"
+ 'auto'
end
end
end
@@ -47,7 +47,7 @@ def self.instrumentation_value_from_boolean(key)
# Marks the config option as deprecated in the documentation once generated.
# Does not appear in logs.
def self.deprecated_description(new_setting, description)
- link_ref = new_setting.to_s.tr(".", "-")
+ link_ref = new_setting.to_s.tr('.', '-')
%{Please see: [#{new_setting}](docs/agents/ruby-agent/configuration/ruby-agent-configuration##{link_ref}). \n\n#{description}}
end
@@ -80,34 +80,35 @@ def self.transform_for(key)
default_settings[:transform] if default_settings
end
- def self.config_search_paths
+ def self.config_search_paths # rubocop:disable Metrics/AbcSize
proc {
- paths = [
- File.join("config", "newrelic.yml"),
- File.join("newrelic.yml"),
- File.join("config", "newrelic.yml.erb"),
- File.join("newrelic.yml.erb")
- ]
+ yaml = 'newrelic.yml'
+ config_yaml = File.join('config', yaml)
+ erb = 'newrelic.yml.erb'
+ config_erb = File.join('config', erb)
+
+ paths = [config_yaml, yaml, config_erb, erb]
if NewRelic::Control.instance.root
- paths << File.join(NewRelic::Control.instance.root, "config", "newrelic.yml")
- paths << File.join(NewRelic::Control.instance.root, "newrelic.yml")
- paths << File.join(NewRelic::Control.instance.root, "config", "newrelic.yml.erb")
- paths << File.join(NewRelic::Control.instance.root, "newrelic.yml.erb")
+ paths << File.join(NewRelic::Control.instance.root, config_yaml)
+ paths << File.join(NewRelic::Control.instance.root, yaml)
+ paths << File.join(NewRelic::Control.instance.root, config_erb)
+ paths << File.join(NewRelic::Control.instance.root, erb)
end
if ENV['HOME']
- paths << File.join(ENV['HOME'], ".newrelic", "newrelic.yml")
- paths << File.join(ENV['HOME'], "newrelic.yml")
- paths << File.join(ENV['HOME'], ".newrelic", "newrelic.yml.erb")
- paths << File.join(ENV['HOME'], "newrelic.yml.erb")
+ paths << File.join(ENV['HOME'], '.newrelic', yaml)
+ paths << File.join(ENV['HOME'], yaml)
+ paths << File.join(ENV['HOME'], '.newrelic', erb)
+ paths << File.join(ENV['HOME'], erb)
end
# If we're packaged for warbler, we can tell from GEM_HOME
- if ENV["GEM_HOME"] && ENV["GEM_HOME"].end_with?(".jar!")
- app_name = File.basename(ENV["GEM_HOME"], ".jar!")
- paths << File.join(ENV["GEM_HOME"], app_name, "config", "newrelic.yml")
- paths << File.join(ENV["GEM_HOME"], app_name, "config", "newrelic.yml.erb")
+ # the following line needs else branch coverage
+ if ENV['GEM_HOME'] && ENV['GEM_HOME'].end_with?('.jar!') # rubocop:disable Style/SafeNavigation
+ app_name = File.basename(ENV['GEM_HOME'], '.jar!')
+ paths << File.join(ENV['GEM_HOME'], app_name, config_yaml)
+ paths << File.join(ENV['GEM_HOME'], app_name, config_erb)
end
paths
@@ -206,11 +207,11 @@ def self.api_host
# only used for deployment task
proc do
api_version = if NewRelic::Agent.config[:api_key].nil? || NewRelic::Agent.config[:api_key].empty?
- "rpm"
+ 'rpm'
else
- "api"
+ 'api'
end
- api_region = "eu." if String(NewRelic::Agent.config[:license_key]).start_with?('eu')
+ api_region = 'eu.' if String(NewRelic::Agent.config[:license_key]).start_with?('eu')
"#{api_version}.#{api_region}newrelic.com"
end
@@ -432,7 +433,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:public => true,
:type => Boolean,
:allowed_from_server => true,
- :description => "Allows newrelic distributed tracing headers to be suppressed on outbound requests."
+ :description => 'Allows newrelic distributed tracing headers to be suppressed on outbound requests.'
},
:force_install_exit_handler => {
:default => false,
@@ -959,7 +960,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:description => 'If `true`, enables an audit log which logs communications with the New Relic [collector](/docs/using-new-relic/welcome-new-relic/get-started/glossary/#collector).'
},
:'audit_log.endpoints' => {
- :default => [".*"],
+ :default => ['.*'],
:public => true,
:type => Array,
:allowed_from_server => false,
@@ -1281,10 +1282,10 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:allowed_from_server => false,
:external => :infinite_tracing,
- :description => "Configures the hostname for the trace observer Host. " \
- "When configured, enables tail-based sampling by sending all recorded spans " \
- "to a trace observer for further sampling decisions, irrespective of any usual " \
- "agent sampling decision."
+ :description => 'Configures the hostname for the trace observer Host. ' \
+ 'When configured, enables tail-based sampling by sending all recorded spans ' \
+ 'to a trace observer for further sampling decisions, irrespective of any usual ' \
+ 'agent sampling decision.'
},
:'infinite_tracing.trace_observer.port' => {
:default => 443,
@@ -1292,7 +1293,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => Integer,
:allowed_from_server => false,
:external => :infinite_tracing,
- :description => "Configures the TCP/IP port for the trace observer Host"
+ :description => 'Configures the TCP/IP port for the trace observer Host'
},
# Instrumentation
:'instrumentation.active_support_logger' => {
@@ -1361,7 +1362,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of Excon at start up. May be one of [enabled|disabled]."
+ :description => 'Controls auto-instrumentation of Excon at start up. May be one of [enabled|disabled].'
},
:'instrumentation.grape' => {
:default => 'auto',
@@ -1369,7 +1370,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of Grape at start up. May be one of [auto|prepend|chain|disabled]."
+ :description => 'Controls auto-instrumentation of Grape at start up. May be one of [auto|prepend|chain|disabled].'
},
:'instrumentation.grpc_client' => {
:default => instrumentation_value_of(:disable_grpc_client),
@@ -1404,7 +1405,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of HTTPClient at start up. May be one of [auto|prepend|chain|disabled]."
+ :description => 'Controls auto-instrumentation of HTTPClient at start up. May be one of [auto|prepend|chain|disabled].'
},
:'instrumentation.httprb' => {
:default => 'auto',
@@ -1457,7 +1458,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of Mongo at start up. May be one of [enabled|disabled]."
+ :description => 'Controls auto-instrumentation of Mongo at start up. May be one of [enabled|disabled].'
},
:'instrumentation.net_http' => {
:default => 'auto',
@@ -1466,7 +1467,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of Net::HTTP at start up. May be one of [auto|prepend|chain|disabled]."
+ :description => 'Controls auto-instrumentation of Net::HTTP at start up. May be one of [auto|prepend|chain|disabled].'
},
:'instrumentation.puma_rack' => {
:default => value_of(:'instrumentation.rack'),
@@ -1475,9 +1476,9 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of Puma::Rack. When enabled, the agent hooks into the " \
- "`to_app` method in Puma::Rack::Builder to find gems to instrument during " \
- "application startup. May be one of [auto|prepend|chain|disabled]."
+ :description => 'Controls auto-instrumentation of Puma::Rack. When enabled, the agent hooks into the ' \
+ '`to_app` method in Puma::Rack::Builder to find gems to instrument during ' \
+ 'application startup. May be one of [auto|prepend|chain|disabled].'
},
:'instrumentation.puma_rack_urlmap' => {
:default => value_of(:'instrumentation.rack_urlmap'),
@@ -1495,9 +1496,9 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of Rack. When enabled, the agent hooks into the " \
- "`to_app` method in Rack::Builder to find gems to instrument during " \
- "application startup. May be one of [auto|prepend|chain|disabled]."
+ :description => 'Controls auto-instrumentation of Rack. When enabled, the agent hooks into the ' \
+ '`to_app` method in Rack::Builder to find gems to instrument during ' \
+ 'application startup. May be one of [auto|prepend|chain|disabled].'
},
:'instrumentation.rack_urlmap' => {
:default => 'auto',
@@ -1514,7 +1515,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of rake at start up. May be one of [auto|prepend|chain|disabled]."
+ :description => 'Controls auto-instrumentation of rake at start up. May be one of [auto|prepend|chain|disabled].'
},
:'instrumentation.redis' => {
:default => 'auto',
@@ -1522,7 +1523,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of Redis at start up. May be one of [auto|prepend|chain|disabled]."
+ :description => 'Controls auto-instrumentation of Redis at start up. May be one of [auto|prepend|chain|disabled].'
},
:'instrumentation.resque' => {
:default => 'auto',
@@ -1531,7 +1532,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of resque at start up. May be one of [auto|prepend|chain|disabled]."
+ :description => 'Controls auto-instrumentation of resque at start up. May be one of [auto|prepend|chain|disabled].'
},
:'instrumentation.sinatra' => {
:default => 'auto',
@@ -1539,7 +1540,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of Sinatra at start up. May be one of [auto|prepend|chain|disabled]."
+ :description => 'Controls auto-instrumentation of Sinatra at start up. May be one of [auto|prepend|chain|disabled].'
},
:'instrumentation.thread' => {
:default => 'auto',
@@ -1547,24 +1548,24 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of the Thread class at start up to allow the agent to correctly nest spans inside of an asynchronous transaction. This does not enable the agent to automatically trace all threads created (see `instrumentation.thread.tracing`). May be one of [auto|prepend|chain|disabled]."
+ :description => 'Controls auto-instrumentation of the Thread class at start up to allow the agent to correctly nest spans inside of an asynchronous transaction. This does not enable the agent to automatically trace all threads created (see `instrumentation.thread.tracing`). May be one of [auto|prepend|chain|disabled].'
},
:'instrumentation.thread.tracing' => {
:default => true,
:public => true,
:type => Boolean,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of the Thread class at start up to automatically add tracing to all Threads created in the application."
+ :description => 'Controls auto-instrumentation of the Thread class at start up to automatically add tracing to all Threads created in the application.'
},
:'thread_ids_enabled' => {
:default => false,
:public => false,
:type => Boolean,
:allowed_from_server => false,
- :description => "If enabled, will append the current Thread and Fiber object ids onto the segment names of segments created in Threads and concurrent-ruby"
+ :description => 'If enabled, will append the current Thread and Fiber object ids onto the segment names of segments created in Threads and concurrent-ruby'
},
:'instrumentation.tilt' => {
- :default => "auto",
+ :default => 'auto',
:public => true,
:type => String,
:dynamic_name => true,
@@ -1578,7 +1579,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => String,
:dynamic_name => true,
:allowed_from_server => false,
- :description => "Controls auto-instrumentation of Typhoeus at start up. May be one of [auto|prepend|chain|disabled]."
+ :description => 'Controls auto-instrumentation of Typhoeus at start up. May be one of [auto|prepend|chain|disabled].'
},
# Message tracer
:'message_tracer.segment_parameters.enabled' => {
@@ -1709,7 +1710,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:type => Integer,
:allowed_from_server => false,
:external => :infinite_tracing,
- :description => "Sets the maximum number of span events to buffer when streaming to the trace observer."
+ :description => 'Sets the maximum number of span events to buffer when streaming to the trace observer.'
},
:'span_events.max_samples_stored' => {
:default => 2000,
@@ -2016,7 +2017,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:public => false,
:type => String,
:allowed_from_server => false,
- :description => "URI for the New Relic data collection service."
+ :description => 'URI for the New Relic data collection service.'
},
:'infinite_tracing.batching' => {
:default => true,
@@ -2025,7 +2026,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil)
:allowed_from_server => false,
:external => :infinite_tracing,
:description => "If `true` (the default), data sent to the trace observer is batched\ninstead of sending " \
- "each span individually."
+ 'each span individually.'
},
:'infinite_tracing.compression_level' => {
:default => :high,
diff --git a/lib/new_relic/agent/configuration/environment_source.rb b/lib/new_relic/agent/configuration/environment_source.rb
index b1e2a0c3a4..f5eadb4f2f 100644
--- a/lib/new_relic/agent/configuration/environment_source.rb
+++ b/lib/new_relic/agent/configuration/environment_source.rb
@@ -94,14 +94,14 @@ def set_key_by_type(config_key, environment_key)
elsif type == Array
self[config_key] = value.split(/\s*,\s*/)
elsif type == NewRelic::Agent::Configuration::Boolean
- if value =~ /false|off|no/i
+ if /false|off|no/i.match?(value)
self[config_key] = false
elsif !value.nil?
self[config_key] = true
end
else
::NewRelic::Agent.logger.info("#{environment_key} does not have a corresponding configuration setting (#{config_key} does not exist).")
- ::NewRelic::Agent.logger.info("Run `rake newrelic:config:docs` or visit https://newrelic.com/docs/ruby/ruby-agent-configuration to see a list of available configuration settings.")
+ ::NewRelic::Agent.logger.info('Run `rake newrelic:config:docs` or visit https://newrelic.com/docs/ruby/ruby-agent-configuration to see a list of available configuration settings.')
self[config_key] = value
end
end
diff --git a/lib/new_relic/agent/configuration/high_security_source.rb b/lib/new_relic/agent/configuration/high_security_source.rb
index 23f7a0a205..9e57ffa246 100644
--- a/lib/new_relic/agent/configuration/high_security_source.rb
+++ b/lib/new_relic/agent/configuration/high_security_source.rb
@@ -24,9 +24,9 @@ def initialize(local_settings)
})
end
- OFF = "off".freeze
- RAW = "raw".freeze
- OBFUSCATED = "obfuscated".freeze
+ OFF = 'off'.freeze
+ RAW = 'raw'.freeze
+ OBFUSCATED = 'obfuscated'.freeze
SET_TO_OBFUSCATED = [RAW, OBFUSCATED]
diff --git a/lib/new_relic/agent/configuration/manager.rb b/lib/new_relic/agent/configuration/manager.rb
index 838da230d9..7254db4731 100644
--- a/lib/new_relic/agent/configuration/manager.rb
+++ b/lib/new_relic/agent/configuration/manager.rb
@@ -241,8 +241,8 @@ def to_collector_hash
end
end
- MALFORMED_LABELS_WARNING = "Skipping malformed labels configuration"
- PARSING_LABELS_FAILURE = "Failure during parsing labels. Ignoring and carrying on with connect."
+ MALFORMED_LABELS_WARNING = 'Skipping malformed labels configuration'
+ PARSING_LABELS_FAILURE = 'Failure during parsing labels. Ignoring and carrying on with connect.'
MAX_LABEL_COUNT = 64
MAX_LABEL_LENGTH = 255
diff --git a/lib/new_relic/agent/configuration/security_policy_source.rb b/lib/new_relic/agent/configuration/security_policy_source.rb
index d21132cbf7..1e4c27338e 100644
--- a/lib/new_relic/agent/configuration/security_policy_source.rb
+++ b/lib/new_relic/agent/configuration/security_policy_source.rb
@@ -51,7 +51,7 @@ def change_setting(policies, option, new_value)
# permitted by the security policy and is also enabled by the config
SECURITY_SETTINGS_MAP = {
- "record_sql" => [
+ 'record_sql' => [
{
option: :'transaction_tracer.record_sql',
supported: true,
@@ -96,7 +96,7 @@ def change_setting(policies, option, new_value)
permitted_fn: nil
}
],
- "attributes_include" => [
+ 'attributes_include' => [
{
option: :'attributes.include',
supported: true,
@@ -147,7 +147,7 @@ def change_setting(policies, option, new_value)
permitted_fn: nil
}
],
- "allow_raw_exception_messages" => [
+ 'allow_raw_exception_messages' => [
{
option: :'strip_exception_messages.enabled',
supported: true,
@@ -156,7 +156,7 @@ def change_setting(policies, option, new_value)
permitted_fn: nil
}
],
- "custom_events" => [
+ 'custom_events' => [
{
option: :'custom_insights_events.enabled',
supported: true,
@@ -165,7 +165,7 @@ def change_setting(policies, option, new_value)
permitted_fn: nil
}
],
- "custom_parameters" => [
+ 'custom_parameters' => [
{
option: :'custom_attributes.enabled',
supported: true,
@@ -174,7 +174,7 @@ def change_setting(policies, option, new_value)
permitted_fn: nil
}
],
- "custom_instrumentation_editor" => [
+ 'custom_instrumentation_editor' => [
{
option: nil,
supported: false,
@@ -183,7 +183,7 @@ def change_setting(policies, option, new_value)
permitted_fn: nil
}
],
- "message_parameters" => [
+ 'message_parameters' => [
{
option: :'message_tracer.segment_parameters.enabled',
supported: true,
@@ -198,8 +198,8 @@ def initialize(security_policies)
super(build_overrides(security_policies))
end
- ENABLED = "enabled".freeze
- COLON_COLON = "::".freeze
+ ENABLED = 'enabled'.freeze
+ COLON_COLON = '::'.freeze
def build_overrides(security_policies)
security_policies.inject({}) do |settings, (policy_name, policy_settings)|
@@ -222,7 +222,7 @@ def build_overrides(security_policies)
settings[policy[:option]] = policy[:disabled_value]
NewRelic::Agent.logger.info( \
"Setting applied: {#{policy[:option]}: #{policy[:disabled_value]}}. " \
- "Source: SecurityPolicySource"
+ 'Source: SecurityPolicySource'
)
end
end
diff --git a/lib/new_relic/agent/configuration/server_source.rb b/lib/new_relic/agent/configuration/server_source.rb
index 91af81afde..4570af338a 100644
--- a/lib/new_relic/agent/configuration/server_source.rb
+++ b/lib/new_relic/agent/configuration/server_source.rb
@@ -10,27 +10,27 @@ class ServerSource < DottedHash
# response, but should still be merged in as config settings to the
# main agent configuration.
TOP_LEVEL_KEYS = [
- "account_id",
- "apdex_t",
- "application_id",
- "beacon",
- "browser_key",
- "browser_monitoring.debug",
- "browser_monitoring.loader",
- "browser_monitoring.loader_version",
- "cross_process_id",
- "data_report_period",
- "encoding_key",
- "entity_guid",
- "error_beacon",
- "js_agent_file",
- "js_agent_loader",
- "max_payload_size_in_bytes",
- "primary_application_id",
- "sampling_target",
- "sampling_target_period_in_seconds",
- "trusted_account_ids",
- "trusted_account_key"
+ 'account_id',
+ 'apdex_t',
+ 'application_id',
+ 'beacon',
+ 'browser_key',
+ 'browser_monitoring.debug',
+ 'browser_monitoring.loader',
+ 'browser_monitoring.loader_version',
+ 'cross_process_id',
+ 'data_report_period',
+ 'encoding_key',
+ 'entity_guid',
+ 'error_beacon',
+ 'js_agent_file',
+ 'js_agent_loader',
+ 'max_payload_size_in_bytes',
+ 'primary_application_id',
+ 'sampling_target',
+ 'sampling_target_period_in_seconds',
+ 'trusted_account_ids',
+ 'trusted_account_key'
]
def initialize(connect_reply, existing_config = {})
@@ -70,7 +70,7 @@ def merge_agent_config_hash(merged_settings, connect_reply)
def fix_transaction_threshold(merged_settings)
# when value is "apdex_f" remove the config and defer to default
- if merged_settings['transaction_tracer.transaction_threshold'].to_s =~ /apdex_f/i
+ if /apdex_f/i.match?(merged_settings['transaction_tracer.transaction_threshold'].to_s)
merged_settings.delete('transaction_tracer.transaction_threshold')
end
end
@@ -102,8 +102,8 @@ def event_harvest_config_is_valid(connect_reply)
if event_harvest_config.nil? \
|| event_harvest_config['harvest_limits'].values.min < 0 \
|| (event_harvest_config['report_period_ms'] / 1000) <= 0
- NewRelic::Agent.logger.warn("Invalid event harvest config found " \
- "in connect response; using default event report period.")
+ NewRelic::Agent.logger.warn('Invalid event harvest config found ' \
+ 'in connect response; using default event report period.')
false
else
true
diff --git a/lib/new_relic/agent/configuration/yaml_source.rb b/lib/new_relic/agent/configuration/yaml_source.rb
index 85535344f7..81a99e40f4 100644
--- a/lib/new_relic/agent/configuration/yaml_source.rb
+++ b/lib/new_relic/agent/configuration/yaml_source.rb
@@ -84,7 +84,7 @@ def warn_missing_config_file(path)
# so warn about it since it's very likely to be unintended.
NewRelic::Agent.logger.warn(
"No configuration file found. Working directory = #{Dir.pwd}",
- "Looked in these locations (based on #{based_on}): #{candidate_paths.join(", ")}"
+ "Looked in these locations (based on #{based_on}): #{candidate_paths.join(', ')}"
)
end
@@ -96,7 +96,7 @@ def process_erb(file)
file.gsub!(/^\s*#.*$/, '#')
ERB.new(file).result(binding)
rescue ScriptError, StandardError => e
- log_failure("Failed ERB processing configuration file. This is typically caused by a Ruby error in <% %> templating blocks in your newrelic.yml file.", e)
+ log_failure('Failed ERB processing configuration file. This is typically caused by a Ruby error in <% %> templating blocks in your newrelic.yml file.', e)
nil
end
end
@@ -124,7 +124,7 @@ def substitute_transaction_threshold(config)
config['transaction_tracer']['transaction_threshold'].to_s =~ /apdex_f/i
# when value is "apdex_f" remove the config and defer to default
config['transaction_tracer'].delete('transaction_threshold')
- elsif config['transaction_tracer.transaction_threshold'].to_s =~ /apdex_f/i
+ elsif /apdex_f/i.match?(config['transaction_tracer.transaction_threshold'].to_s)
config.delete('transaction_tracer.transaction_threshold')
end
end
@@ -135,7 +135,7 @@ def booleanify_values(config, *keys)
if 'auto' == config[option]
config.delete(option)
elsif !config[option].nil? && !is_boolean?(config[option])
- coerced_value = !!(config[option].to_s =~ /yes|on|true/i)
+ coerced_value = config[option].to_s.match?(/yes|on|true/i)
if !coerced_value
log_failure("Unexpected value (#{config[option]}) for '#{option}' in #{@path}")
end
diff --git a/lib/new_relic/agent/connect/request_builder.rb b/lib/new_relic/agent/connect/request_builder.rb
index f9639231b1..2d852d5e76 100644
--- a/lib/new_relic/agent/connect/request_builder.rb
+++ b/lib/new_relic/agent/connect/request_builder.rb
@@ -48,7 +48,7 @@ def sanitize_environment_report(environment_report)
def environment_metadata
env_copy = {}
- ENV.keys.each { |k| env_copy[k] = ENV[k] if k =~ /^NEW_RELIC_METADATA_/ }
+ ENV.keys.each { |k| env_copy[k] = ENV[k] if /^NEW_RELIC_METADATA_/.match?(k) }
env_copy
end
diff --git a/lib/new_relic/agent/connect/response_handler.rb b/lib/new_relic/agent/connect/response_handler.rb
index 6be46bfd7c..ec469d6c9f 100644
--- a/lib/new_relic/agent/connect/response_handler.rb
+++ b/lib/new_relic/agent/connect/response_handler.rb
@@ -37,7 +37,7 @@ def configure_agent(config_data)
def add_server_side_config(config_data)
if config_data['agent_config']
- ::NewRelic::Agent.logger.debug("Using config from server")
+ ::NewRelic::Agent.logger.debug('Using config from server')
end
::NewRelic::Agent.logger.debug("Server provided config: #{config_data.inspect}")
diff --git a/lib/new_relic/agent/custom_event_aggregator.rb b/lib/new_relic/agent/custom_event_aggregator.rb
index 5af3cf9aad..c15596fd89 100644
--- a/lib/new_relic/agent/custom_event_aggregator.rb
+++ b/lib/new_relic/agent/custom_event_aggregator.rb
@@ -27,7 +27,7 @@ def record(type, attributes)
return unless enabled?
type = @type_strings[type]
- unless type =~ EVENT_TYPE_REGEX
+ unless EVENT_TYPE_REGEX.match?(type)
note_dropped_event(type)
return false
end
@@ -71,9 +71,9 @@ def note_dropped_events(total_count, dropped_count)
def record_supportability_metrics(total_count, captured_count, dropped_count)
engine = NewRelic::Agent.instance.stats_engine
- engine.tl_record_supportability_metric_count("Events/Customer/Seen", total_count)
- engine.tl_record_supportability_metric_count("Events/Customer/Sent", captured_count)
- engine.tl_record_supportability_metric_count("Events/Customer/Dropped", dropped_count)
+ engine.tl_record_supportability_metric_count('Events/Customer/Seen', total_count)
+ engine.tl_record_supportability_metric_count('Events/Customer/Sent', captured_count)
+ engine.tl_record_supportability_metric_count('Events/Customer/Dropped', dropped_count)
end
def note_dropped_event(type)
diff --git a/lib/new_relic/agent/database.rb b/lib/new_relic/agent/database.rb
index 20f03b37c6..63b25c8f08 100644
--- a/lib/new_relic/agent/database.rb
+++ b/lib/new_relic/agent/database.rb
@@ -10,7 +10,7 @@ module NewRelic
module Agent
module Database
MAX_QUERY_LENGTH = 16384
- ELLIPSIS = "...".freeze
+ ELLIPSIS = '...'.freeze
extend self
@@ -150,7 +150,7 @@ def get_connection(config, &connector)
begin
@connections[config] = yield(config)
rescue => e
- ::NewRelic::Agent.logger.error("Caught exception trying to get connection to DB for explain.", e)
+ ::NewRelic::Agent.logger.error('Caught exception trying to get connection to DB for explain.', e)
nil
end
end
@@ -174,7 +174,7 @@ class Statement
attr_accessor :sql, :config, :explainer, :binds, :name, :host, :port_path_or_id, :database_name
- DEFAULT_QUERY_NAME = "SQL".freeze
+ DEFAULT_QUERY_NAME = 'SQL'.freeze
def initialize(sql, config = {}, explainer = nil, binds = nil, name = DEFAULT_QUERY_NAME, host = nil, port_path_or_id = nil, database_name = nil)
@sql = Database.capture_query(sql)
@@ -219,7 +219,7 @@ def explain
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
plan = @explainer.call(self)
::NewRelic::Agent.record_metric(
- "Supportability/Database/execute_explain_plan",
+ 'Supportability/Database/execute_explain_plan',
Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
)
return process_resultset(plan, adapter) if plan
diff --git a/lib/new_relic/agent/database/explain_plan_helpers.rb b/lib/new_relic/agent/database/explain_plan_helpers.rb
index e851c72c37..55977fa16a 100644
--- a/lib/new_relic/agent/database/explain_plan_helpers.rb
+++ b/lib/new_relic/agent/database/explain_plan_helpers.rb
@@ -36,7 +36,7 @@ def handle_exception_in_explain
rescue => e
begin
# guarantees no throw from explain_sql
- ::NewRelic::Agent.logger.error("Error getting query plan:", e)
+ ::NewRelic::Agent.logger.error('Error getting query plan:', e)
nil
rescue
# double exception. throw up your hands
diff --git a/lib/new_relic/agent/database/obfuscation_helpers.rb b/lib/new_relic/agent/database/obfuscation_helpers.rb
index 3b76783f6b..12ae7fd043 100644
--- a/lib/new_relic/agent/database/obfuscation_helpers.rb
+++ b/lib/new_relic/agent/database/obfuscation_helpers.rb
@@ -49,10 +49,10 @@ module ObfuscationHelpers
}
PLACEHOLDER = '?'.freeze
- FAILED_TO_OBFUSCATE_MESSAGE = "Failed to obfuscate SQL query - quote characters remained after obfuscation".freeze
+ FAILED_TO_OBFUSCATE_MESSAGE = 'Failed to obfuscate SQL query - quote characters remained after obfuscation'.freeze
def obfuscate_single_quote_literals(sql)
- return sql unless sql =~ COMPONENTS_REGEX_MAP[:single_quotes]
+ return sql unless sql&.match?(COMPONENTS_REGEX_MAP[:single_quotes])
sql.gsub(COMPONENTS_REGEX_MAP[:single_quotes], PLACEHOLDER)
end
diff --git a/lib/new_relic/agent/database/obfuscator.rb b/lib/new_relic/agent/database/obfuscator.rb
index 483f56887b..0a90dcdb6c 100644
--- a/lib/new_relic/agent/database/obfuscator.rb
+++ b/lib/new_relic/agent/database/obfuscator.rb
@@ -13,8 +13,8 @@ class Obfuscator
attr_reader :obfuscator
- QUERY_TOO_LARGE_MESSAGE = "Query too large (over 16k characters) to safely obfuscate".freeze
- ELLIPSIS = "...".freeze
+ QUERY_TOO_LARGE_MESSAGE = 'Query too large (over 16k characters) to safely obfuscate'.freeze
+ ELLIPSIS = '...'.freeze
def initialize
reset
diff --git a/lib/new_relic/agent/datastores/metric_helper.rb b/lib/new_relic/agent/datastores/metric_helper.rb
index f2ba77d8b9..10d5d66151 100644
--- a/lib/new_relic/agent/datastores/metric_helper.rb
+++ b/lib/new_relic/agent/datastores/metric_helper.rb
@@ -6,12 +6,12 @@ module NewRelic
module Agent
module Datastores
module MetricHelper
- ROLLUP_METRIC = "Datastore/all".freeze
- OTHER = "Other".freeze
+ ROLLUP_METRIC = 'Datastore/all'.freeze
+ OTHER = 'Other'.freeze
- ALL = "all".freeze
- ALL_WEB = "allWeb".freeze
- ALL_OTHER = "allOther".freeze
+ ALL = 'all'.freeze
+ ALL_WEB = 'allWeb'.freeze
+ ALL_OTHER = 'allOther'.freeze
def self.statement_metric_for(product, collection, operation)
"Datastore/statement/#{product}/#{collection}/#{operation}"
diff --git a/lib/new_relic/agent/datastores/mongo/metric_translator.rb b/lib/new_relic/agent/datastores/mongo/metric_translator.rb
index 774b7f24d9..9ba30ef232 100644
--- a/lib/new_relic/agent/datastores/mongo/metric_translator.rb
+++ b/lib/new_relic/agent/datastores/mongo/metric_translator.rb
@@ -53,7 +53,7 @@ def self.operation_and_collection_for(name, payload)
[name.to_s, collection]
rescue => e
- NewRelic::Agent.logger.debug("Failure during Mongo metric generation", e)
+ NewRelic::Agent.logger.debug('Failure during Mongo metric generation', e)
nil
end
@@ -64,10 +64,10 @@ def self.collection_in_selector?(payload)
NAMES_IN_SELECTOR = [
:findandmodify,
- "aggregate",
- "count",
- "group",
- "mapreduce",
+ 'aggregate',
+ 'count',
+ 'group',
+ 'mapreduce',
:distinct,
@@ -91,18 +91,18 @@ def self.get_name_from_selector(command_key, payload)
if command_key
command_key.to_sym
else
- NewRelic::Agent.increment_metric("Supportability/Mongo/UnknownCollection")
+ NewRelic::Agent.increment_metric('Supportability/Mongo/UnknownCollection')
payload[:selector].first.first unless command_key
end
end
- CMD_COLLECTION = "$cmd".freeze
+ CMD_COLLECTION = '$cmd'.freeze
def self.get_collection_from_selector(command_key, payload)
if command_key
payload[:selector][command_key]
else
- NewRelic::Agent.increment_metric("Supportability/Mongo/UnknownCollection")
+ NewRelic::Agent.increment_metric('Supportability/Mongo/UnknownCollection')
CMD_COLLECTION
end
end
@@ -124,11 +124,11 @@ def self.create_indexes?(name, _payload)
end
def self.create_index?(name, payload)
- name == :insert && payload[:collection] == "system.indexes"
+ name == :insert && payload[:collection] == 'system.indexes'
end
def self.drop_indexes?(name, payload)
- name == :deleteIndexes && payload[:selector] && payload[:selector][:index] == "*"
+ name == :deleteIndexes && payload[:selector] && payload[:selector][:index] == '*'
end
def self.drop_index?(name, payload)
@@ -166,7 +166,7 @@ def self.collection_name_from_index(payload)
end
def self.collection_name_from_group_selector(payload)
- payload[:selector]["group"]["ns"]
+ payload[:selector]['group']['ns']
end
def self.collection_name_from_rename_selector(payload)
diff --git a/lib/new_relic/agent/datastores/redis.rb b/lib/new_relic/agent/datastores/redis.rb
index 031a66535e..ea98baedbe 100644
--- a/lib/new_relic/agent/datastores/redis.rb
+++ b/lib/new_relic/agent/datastores/redis.rb
@@ -6,7 +6,7 @@ module NewRelic
module Agent
module Datastores
module Redis
- BINARY_DATA_PLACEHOLDER = ""
+ BINARY_DATA_PLACEHOLDER = ''
MAXIMUM_COMMAND_LENGTH = 1000
MAXIMUM_ARGUMENT_LENGTH = 64
@@ -25,7 +25,7 @@ module Redis
def self.format_command(command_with_args)
if Agent.config[:'transaction_tracer.record_redis_arguments']
- result = String.new('')
+ result = +''
append_command_with_args(result, command_with_args)
@@ -36,7 +36,7 @@ def self.format_command(command_with_args)
end
def self.format_pipeline_commands(commands_with_args)
- result = String.new('')
+ result = +''
commands_with_args.each do |command|
if result.length >= MAXIMUM_COMMAND_LENGTH
@@ -83,7 +83,7 @@ def self.append_command_with_no_args(result, command_with_args)
end
def self.is_supported_version?
- Gem::Version.new(::Redis::VERSION) >= Gem::Version.new("3.0.0")
+ Gem::Version.new(::Redis::VERSION) >= Gem::Version.new('3.0.0')
end
def self.ellipsize(result, string)
@@ -106,8 +106,8 @@ def self.ellipsize(result, string)
end
def self.safe_from_third_party_gem?
- if NewRelic::LanguageSupport.bundled_gem?("newrelic-redis")
- ::NewRelic::Agent.logger.info("Not installing New Relic supported Redis instrumentation because the third party newrelic-redis gem is present")
+ if NewRelic::LanguageSupport.bundled_gem?('newrelic-redis')
+ ::NewRelic::Agent.logger.info('Not installing New Relic supported Redis instrumentation because the third party newrelic-redis gem is present')
false
else
true
diff --git a/lib/new_relic/agent/distributed_tracing.rb b/lib/new_relic/agent/distributed_tracing.rb
index 601dc58a80..9a48023a21 100644
--- a/lib/new_relic/agent/distributed_tracing.rb
+++ b/lib/new_relic/agent/distributed_tracing.rb
@@ -45,11 +45,11 @@ def insert_distributed_trace_headers(headers = {})
record_api_supportability_metric(:insert_distributed_trace_headers)
unless Agent.config[:'distributed_tracing.enabled']
- NewRelic::Agent.logger.warn("Not configured to insert distributed trace headers")
+ NewRelic::Agent.logger.warn('Not configured to insert distributed trace headers')
return nil
end
- return unless valid_api_argument_class?(headers, "headers", Hash)
+ return unless valid_api_argument_class?(headers, 'headers', Hash)
return unless transaction = Transaction.tl_current
@@ -99,12 +99,12 @@ def accept_distributed_trace_headers(headers, transport_type = NewRelic::HTTP)
record_api_supportability_metric(:accept_distributed_trace_headers)
unless Agent.config[:'distributed_tracing.enabled']
- NewRelic::Agent.logger.warn("Not configured to accept distributed trace headers")
+ NewRelic::Agent.logger.warn('Not configured to accept distributed trace headers')
return nil
end
- return unless valid_api_argument_class?(headers, "headers", Hash)
- return unless valid_api_argument_class?(transport_type, "transport_type", String)
+ return unless valid_api_argument_class?(headers, 'headers', Hash)
+ return unless valid_api_argument_class?(transport_type, 'transport_type', String)
return unless transaction = Transaction.tl_current
diff --git a/lib/new_relic/agent/distributed_tracing/cross_app_tracing.rb b/lib/new_relic/agent/distributed_tracing/cross_app_tracing.rb
index 456098818d..aa85ba83a4 100644
--- a/lib/new_relic/agent/distributed_tracing/cross_app_tracing.rb
+++ b/lib/new_relic/agent/distributed_tracing/cross_app_tracing.rb
@@ -1,4 +1,3 @@
-# -*- ruby -*-
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
# frozen_string_literal: true
@@ -28,7 +27,7 @@ def is_cross_app_caller?
end
def is_cross_app_callee?
- cross_app_payload != nil
+ !cross_app_payload.nil?
end
def is_cross_app?
@@ -36,7 +35,7 @@ def is_cross_app?
end
def cat_trip_id
- cross_app_payload && cross_app_payload.referring_trip_id || transaction.guid
+ cross_app_payload&.referring_trip_id || transaction.guid
end
def cross_app_monitor
@@ -74,7 +73,7 @@ def add_message_cat_headers(headers)
end
def record_cross_app_metrics
- if (id = cross_app_payload && cross_app_payload.id)
+ if (id = cross_app_payload&.id)
app_time_in_seconds = [
Process.clock_gettime(Process::CLOCK_REALTIME) - transaction.start_time,
0.0
@@ -104,11 +103,11 @@ def record_cat_path_hash(hash)
end
def cat_referring_path_hash
- cross_app_payload && cross_app_payload.referring_path_hash
+ cross_app_payload&.referring_path_hash
end
def append_cat_info(payload)
- if (referring_guid = cross_app_payload && cross_app_payload.referring_guid)
+ if (referring_guid = cross_app_payload&.referring_guid)
payload[:referring_transaction_guid] = referring_guid
end
@@ -150,7 +149,7 @@ def valid_cross_process_id?
if Agent.config[:cross_process_id] && Agent.config[:cross_process_id].length > 0
true
else
- NewRelic::Agent.logger.debug("No cross_process_id configured")
+ NewRelic::Agent.logger.debug('No cross_process_id configured')
false
end
end
@@ -159,7 +158,7 @@ def valid_encoding_key?
if Agent.config[:encoding_key] && Agent.config[:encoding_key].length > 0
true
else
- NewRelic::Agent.logger.debug("No encoding_key set")
+ NewRelic::Agent.logger.debug('No encoding_key set')
false
end
end
diff --git a/lib/new_relic/agent/distributed_tracing/distributed_trace_attributes.rb b/lib/new_relic/agent/distributed_tracing/distributed_trace_attributes.rb
index 8f6c0acfcf..592ffa6c30 100644
--- a/lib/new_relic/agent/distributed_tracing/distributed_trace_attributes.rb
+++ b/lib/new_relic/agent/distributed_tracing/distributed_trace_attributes.rb
@@ -9,16 +9,16 @@ module DistributedTraceAttributes
# Intrinsic Keys
INTRINSIC_KEYS = [
- PARENT_TYPE_KEY = "parent.type",
- PARENT_APP_KEY = "parent.app",
- PARENT_ACCOUNT_ID_KEY = "parent.account",
- PARENT_TRANSPORT_TYPE_KEY = "parent.transportType",
- PARENT_TRANSPORT_DURATION_KEY = "parent.transportDuration",
- GUID_KEY = "guid",
- TRACE_ID_KEY = "traceId",
- PARENT_TRANSACTION_ID_KEY = "parentId",
- PARENT_SPAN_ID_KEY = "parentSpanId",
- SAMPLED_KEY = "sampled"
+ PARENT_TYPE_KEY = 'parent.type',
+ PARENT_APP_KEY = 'parent.app',
+ PARENT_ACCOUNT_ID_KEY = 'parent.account',
+ PARENT_TRANSPORT_TYPE_KEY = 'parent.transportType',
+ PARENT_TRANSPORT_DURATION_KEY = 'parent.transportDuration',
+ GUID_KEY = 'guid',
+ TRACE_ID_KEY = 'traceId',
+ PARENT_TRANSACTION_ID_KEY = 'parentId',
+ PARENT_SPAN_ID_KEY = 'parentSpanId',
+ SAMPLED_KEY = 'sampled'
].freeze
# This method extracts intrinsics from the transaction_payload and
diff --git a/lib/new_relic/agent/distributed_tracing/distributed_trace_metrics.rb b/lib/new_relic/agent/distributed_tracing/distributed_trace_metrics.rb
index f93b6219dd..39c7f8ac90 100644
--- a/lib/new_relic/agent/distributed_tracing/distributed_trace_metrics.rb
+++ b/lib/new_relic/agent/distributed_tracing/distributed_trace_metrics.rb
@@ -7,11 +7,11 @@ module Agent
module DistributedTraceMetrics
extend self
- ALL_SUFFIX = "all"
- ALL_WEB_SUFFIX = "allWeb"
- ALL_OTHER_SUFFIX = "allOther"
+ ALL_SUFFIX = 'all'
+ ALL_WEB_SUFFIX = 'allWeb'
+ ALL_OTHER_SUFFIX = 'allOther'
- UNKNOWN_CALLER_PREFIX = "%s/Unknown/Unknown/Unknown/%s"
+ UNKNOWN_CALLER_PREFIX = '%s/Unknown/Unknown/Unknown/%s'
def transaction_type_suffix
if Transaction.recording_web_transaction?
@@ -45,14 +45,14 @@ def prefix_for_metric(name, transaction, payload)
end
def record_caller_by_duration_metrics(transaction, payload)
- prefix = prefix_for_metric("DurationByCaller", transaction, payload)
+ prefix = prefix_for_metric('DurationByCaller', transaction, payload)
record_unscoped_metric(transaction, prefix, transaction.duration)
end
def record_transport_duration_metrics(transaction, payload)
return unless payload
- prefix = prefix_for_metric("TransportDuration", transaction, payload)
+ prefix = prefix_for_metric('TransportDuration', transaction, payload)
duration = transaction.calculate_transport_duration(payload)
record_unscoped_metric(transaction, prefix, duration)
end
@@ -60,7 +60,7 @@ def record_transport_duration_metrics(transaction, payload)
def record_errors_by_caller_metrics(transaction, payload)
return unless transaction.exceptions.size > 0
- prefix = prefix_for_metric("ErrorsByCaller", transaction, payload)
+ prefix = prefix_for_metric('ErrorsByCaller', transaction, payload)
record_unscoped_metric(transaction, prefix, 1)
end
diff --git a/lib/new_relic/agent/distributed_tracing/distributed_trace_payload.rb b/lib/new_relic/agent/distributed_tracing/distributed_trace_payload.rb
index 40397279d3..f4f932b0fc 100644
--- a/lib/new_relic/agent/distributed_tracing/distributed_trace_payload.rb
+++ b/lib/new_relic/agent/distributed_tracing/distributed_trace_payload.rb
@@ -17,7 +17,7 @@ class DistributedTracePayload
extend Coerce
VERSION = [0, 1].freeze
- PARENT_TYPE = "App"
+ PARENT_TYPE = 'App'
# Key names for serialization
VERSION_KEY = 'v'
diff --git a/lib/new_relic/agent/distributed_tracing/distributed_trace_transport_type.rb b/lib/new_relic/agent/distributed_tracing/distributed_trace_transport_type.rb
index f52cfc6f97..8e929fff65 100644
--- a/lib/new_relic/agent/distributed_tracing/distributed_trace_transport_type.rb
+++ b/lib/new_relic/agent/distributed_tracing/distributed_trace_transport_type.rb
@@ -11,12 +11,12 @@ module DistributedTraceTransportType
NewRelic::UNKNOWN,
NewRelic::HTTP,
NewRelic::HTTPS,
- "Kafka",
- "JMS",
- "IronMQ",
- "AMQP",
- "Queue",
- "Other"
+ 'Kafka',
+ 'JMS',
+ 'IronMQ',
+ 'AMQP',
+ 'Queue',
+ 'Other'
].freeze
URL_SCHEMES = {
diff --git a/lib/new_relic/agent/distributed_tracing/trace_context.rb b/lib/new_relic/agent/distributed_tracing/trace_context.rb
index c1f29d10ab..d8d3fe9491 100644
--- a/lib/new_relic/agent/distributed_tracing/trace_context.rb
+++ b/lib/new_relic/agent/distributed_tracing/trace_context.rb
@@ -29,14 +29,14 @@ class TraceContext
TP_UNDEFINED_FIELDS = "(?<#{UNDEFINED_FIELDS_KEY}>-[a-zA-Z\\d-]*)"
TRACE_PARENT_REGEX = /\A#{TP_VERSION}-#{TP_TRACE_ID}-#{TP_PARENT_ID}-#{TP_TRACE_FLAGS}#{TP_UNDEFINED_FIELDS}?\z/
- TRACE_PARENT_FORMAT_STRING = "%02x-%s-%s-%02x"
+ TRACE_PARENT_FORMAT_STRING = '%02x-%s-%s-%02x'
MAX_TRACE_STATE_SIZE = 512 # bytes
MAX_TRACE_STATE_ENTRY_SIZE = 128 # bytes
- SUPPORTABILITY_TRACE_PARENT_PARSE_EXCEPTION = "Supportability/TraceContext/TraceParent/Parse/Exception"
- SUPPORTABILITY_TRACE_STATE_PARSE_EXCEPTION = "Supportability/TraceContext/TraceState/Parse/Exception"
- SUPPORTABILITY_TRACE_STATE_INVALID_NR_ENTRY = "Supportability/TraceContext/TraceState/InvalidNrEntry"
+ SUPPORTABILITY_TRACE_PARENT_PARSE_EXCEPTION = 'Supportability/TraceContext/TraceParent/Parse/Exception'
+ SUPPORTABILITY_TRACE_STATE_PARSE_EXCEPTION = 'Supportability/TraceContext/TraceState/Parse/Exception'
+ SUPPORTABILITY_TRACE_STATE_INVALID_NR_ENTRY = 'Supportability/TraceContext/TraceState/InvalidNrEntry'
class << self
def insert(format: NewRelic::FORMAT_NON_RACK,
@@ -78,7 +78,7 @@ def parse(format: NewRelic::FORMAT_NON_RACK,
end
def create_trace_state_entry(entry_key, payload)
- "#{entry_key}=#{payload}".dup
+ +"#{entry_key}=#{payload}"
end
private
@@ -138,7 +138,7 @@ def extract_tracestate(format, carrier, trace_state_entry_key)
payload = nil
trace_state_size = 0
- trace_state_vendors = String.new
+ trace_state_vendors = +''
trace_state = header.split(COMMA).map(&:strip)
trace_state.reject! do |entry|
if entry == NewRelic::EMPTY_STR
@@ -223,7 +223,7 @@ def join_trace_state(trace_state_entry_size)
max_size = MAX_TRACE_STATE_SIZE - trace_state_entry_size
return @trace_state_entries.join(COMMA).prepend(COMMA) if @trace_state_size < max_size
- joined_trace_state = ''.dup
+ joined_trace_state = +''
used_size = 0
diff --git a/lib/new_relic/agent/distributed_tracing/trace_context_payload.rb b/lib/new_relic/agent/distributed_tracing/trace_context_payload.rb
index e32b8a127d..7fe29c011e 100644
--- a/lib/new_relic/agent/distributed_tracing/trace_context_payload.rb
+++ b/lib/new_relic/agent/distributed_tracing/trace_context_payload.rb
@@ -9,8 +9,8 @@ module Agent
class TraceContextPayload
VERSION = 0
PARENT_TYPE = 0
- DELIMITER = "-".freeze
- SUPPORTABILITY_PARSE_EXCEPTION = "Supportability/TraceContext/Parse/Exception".freeze
+ DELIMITER = '-'.freeze
+ SUPPORTABILITY_PARSE_EXCEPTION = 'Supportability/TraceContext/Parse/Exception'.freeze
TRUE_CHAR = '1'.freeze
FALSE_CHAR = '0'.freeze
@@ -64,7 +64,7 @@ def now_ms
def handle_invalid_payload(error: nil, message: nil)
NewRelic::Agent.increment_metric(SUPPORTABILITY_PARSE_EXCEPTION)
if error
- NewRelic::Agent.logger.warn("Error parsing trace context payload", error)
+ NewRelic::Agent.logger.warn('Error parsing trace context payload', error)
elsif message
NewRelic::Agent.logger.warn("Error parsing trace context payload: #{message}")
end
@@ -118,7 +118,7 @@ def to_s
result << DELIMITER << (id || NewRelic::EMPTY_STR)
result << DELIMITER << (transaction_id || NewRelic::EMPTY_STR)
result << DELIMITER << (sampled ? TRUE_CHAR : FALSE_CHAR)
- result << DELIMITER << sprintf("%.6f", priority)
+ result << DELIMITER << sprintf('%.6f', priority)
result << DELIMITER << timestamp.to_s # required
result
end
diff --git a/lib/new_relic/agent/error_collector.rb b/lib/new_relic/agent/error_collector.rb
index 3edb728afb..b04a26213a 100644
--- a/lib/new_relic/agent/error_collector.rb
+++ b/lib/new_relic/agent/error_collector.rb
@@ -156,13 +156,13 @@ def blamed_metric_name(txn, options)
end
def aggregated_metric_names(txn)
- metric_names = ["Errors/all"]
+ metric_names = ['Errors/all']
return metric_names unless txn
if txn.recording_web_transaction?
- metric_names << "Errors/allWeb"
+ metric_names << 'Errors/allWeb'
else
- metric_names << "Errors/allOther"
+ metric_names << 'Errors/allOther'
end
metric_names
@@ -227,7 +227,7 @@ def notice_segment_error(segment, exception, options = {})
def notice_error(exception, options = {}, span_id = nil)
state = ::NewRelic::Agent::Tracer.state
transaction = state.current_transaction
- status_code = transaction ? transaction.http_response_code : nil
+ status_code = transaction&.http_response_code
return if skip_notice_error?(exception, status_code)
@@ -242,8 +242,8 @@ def notice_error(exception, options = {}, span_id = nil)
noticed_error = create_noticed_error(exception, options)
error_trace_aggregator.add_to_error_queue(noticed_error)
transaction = state.current_transaction
- payload = transaction ? transaction.payload : nil
- span_id ||= transaction && transaction.current_segment ? transaction.current_segment.guid : nil
+ payload = transaction&.payload
+ span_id ||= transaction&.current_segment ? transaction.current_segment.guid : nil
error_event_aggregator.record(noticed_error, payload, span_id)
exception
rescue => e
@@ -277,7 +277,7 @@ def create_noticed_error(exception, options)
noticed_error.line_number = sense_method(exception, :line_number)
noticed_error.stack_trace = truncate_trace(extract_stack_trace(exception))
- noticed_error.expected = !!options.delete(:expected) || expected?(exception)
+ noticed_error.expected = !options.delete(:expected).nil? || expected?(exception)
noticed_error.attributes_from_notice_error = options.delete(:custom_params) || {}
@@ -285,6 +285,8 @@ def create_noticed_error(exception, options)
# get treated as custom attributes, so merge them into that hash.
noticed_error.attributes_from_notice_error.merge!(options)
+ update_error_group_name(noticed_error, exception, options)
+
noticed_error
end
@@ -306,6 +308,32 @@ def drop_buffered_data
@error_event_aggregator.reset!
nil
end
+
+ private
+
+ def update_error_group_name(noticed_error, exception, options)
+ return unless error_group_callback
+
+ callback_hash = build_customer_callback_hash(noticed_error, exception, options)
+ result = error_group_callback.call(callback_hash)
+ noticed_error.error_group = result
+ rescue StandardError => e
+ NewRelic::Agent.logger.error("Failed to obtain error group from customer callback: #{e.class} - #{e.message}")
+ end
+
+ def build_customer_callback_hash(noticed_error, exception, options)
+ {error: exception,
+ customAttributes: noticed_error.custom_attributes,
+ 'request.uri': noticed_error.request_uri,
+ 'http.statusCode': noticed_error.agent_attributes[:'http.statusCode'],
+ 'http.method': noticed_error.intrinsic_attributes[:'http.method'],
+ 'error.expected': noticed_error.expected,
+ options: options}
+ end
+
+ def error_group_callback
+ NewRelic::Agent.error_group_callback
+ end
end
end
end
diff --git a/lib/new_relic/agent/error_filter.rb b/lib/new_relic/agent/error_filter.rb
index dd2c49da9a..47b9eb6802 100644
--- a/lib/new_relic/agent/error_filter.rb
+++ b/lib/new_relic/agent/error_filter.rb
@@ -80,7 +80,7 @@ def ignore(*args)
@ignore_messages.update(errors)
log_filter(:ignore_messages, errors)
when String
- if errors =~ /^[\d\,\-]+$/
+ if /^[\d\,\-]+$/.match?(errors)
@ignore_status_codes |= parse_status_codes(errors)
log_filter(:ignore_status_codes, errors)
else
@@ -104,7 +104,7 @@ def expect(*args)
@expected_messages.update(errors)
log_filter(:expected_messages, errors)
when String
- if errors =~ /^[\d\,\-]+$/
+ if /^[\d\,\-]+$/.match?(errors)
@expected_status_codes |= parse_status_codes(errors)
log_filter(:expected_status_codes, errors)
else
diff --git a/lib/new_relic/agent/error_trace_aggregator.rb b/lib/new_relic/agent/error_trace_aggregator.rb
index f0ce048780..8b7f0be28d 100644
--- a/lib/new_relic/agent/error_trace_aggregator.rb
+++ b/lib/new_relic/agent/error_trace_aggregator.rb
@@ -81,13 +81,14 @@ def notice_agent_error(exception)
# Already seen this class once? Bail!
return if @errors.any? { |err| err.exception_class_name == exception.class.name }
- trace = exception.backtrace || caller.dup
- noticed_error = NewRelic::NoticedError.new("NewRelic/AgentError", exception)
- noticed_error.stack_trace = trace
+ noticed_error = NewRelic::Agent.instance.error_collector.create_noticed_error(exception,
+ {metric: 'NewRelic/AgentError'})
+ noticed_error.stack_trace = caller.dup unless exception.backtrace
+
@errors << noticed_error
end
rescue => e
- NewRelic::Agent.logger.info("Unable to capture internal agent error due to an exception:", e)
+ NewRelic::Agent.logger.info('Unable to capture internal agent error due to an exception:', e)
end
def register_config_callbacks
diff --git a/lib/new_relic/agent/event_loop.rb b/lib/new_relic/agent/event_loop.rb
index c1a4887575..6e2b81901a 100644
--- a/lib/new_relic/agent/event_loop.rb
+++ b/lib/new_relic/agent/event_loop.rb
@@ -96,7 +96,7 @@ def stop
end
def run
- ::NewRelic::Agent.logger.debug("Running event loop")
+ ::NewRelic::Agent.logger.debug('Running event loop')
while !stopped?
run_once
end
@@ -161,7 +161,7 @@ def dispatch_event(event, args)
end
def reschedule_timer_for_event(e)
- @timers[e].reschedule if @timers[e]
+ @timers[e]&.reschedule
end
def on(event, &blk)
@@ -187,7 +187,7 @@ def wakeup
begin
@self_pipe_wr.write_nonblock('.')
rescue Errno::EAGAIN
- ::NewRelic::Agent.logger.debug("Failed to wakeup event loop")
+ ::NewRelic::Agent.logger.debug('Failed to wakeup event loop')
end
end
end
diff --git a/lib/new_relic/agent/external.rb b/lib/new_relic/agent/external.rb
index 48cb174d9b..6154f6d019 100644
--- a/lib/new_relic/agent/external.rb
+++ b/lib/new_relic/agent/external.rb
@@ -97,7 +97,7 @@ def get_response_metadata
obfuscator.obfuscate(::JSON.dump(rmd))
end
rescue => e
- NewRelic::Agent.logger.error("error during get_response_metadata", e)
+ NewRelic::Agent.logger.error('error during get_response_metadata', e)
end
private
diff --git a/lib/new_relic/agent/harvester.rb b/lib/new_relic/agent/harvester.rb
index fa8d7aae4b..d5a6bb9da9 100644
--- a/lib/new_relic/agent/harvester.rb
+++ b/lib/new_relic/agent/harvester.rb
@@ -14,9 +14,7 @@ def initialize(events, after_forker = NewRelic::Agent)
@starting_pid = nil
@after_forker = after_forker
- if events
- events.subscribe(:start_transaction, &method(:on_transaction))
- end
+ events&.subscribe(:start_transaction, &method(:on_transaction))
end
def on_transaction(*_)
diff --git a/lib/new_relic/agent/heap.rb b/lib/new_relic/agent/heap.rb
index 343636e60f..c00bfff969 100644
--- a/lib/new_relic/agent/heap.rb
+++ b/lib/new_relic/agent/heap.rb
@@ -26,7 +26,8 @@ class Heap
def initialize(items = nil, &priority_fn)
@items = []
@priority_fn = priority_fn || ->(x) { x }
- items.each { |item| push(item) } if items
+ # the following line needs else branch coverage
+ items.each { |item| push(item) } if items # rubocop:disable Style/SafeNavigation
end
def [](index)
diff --git a/lib/new_relic/agent/hostname.rb b/lib/new_relic/agent/hostname.rb
index bcb93ecfd2..2430d247fe 100644
--- a/lib/new_relic/agent/hostname.rb
+++ b/lib/new_relic/agent/hostname.rb
@@ -39,7 +39,7 @@ def self.get_fqdn
def self.heroku_dyno_name_prefix(dyno_name)
get_dyno_prefixes.find do |dyno_prefix|
- dyno_name.start_with?(dyno_prefix + ".")
+ dyno_name.start_with?(dyno_prefix + '.')
end
end
diff --git a/lib/new_relic/agent/http_clients/abstract.rb b/lib/new_relic/agent/http_clients/abstract.rb
index edbeddb490..21f59b1583 100644
--- a/lib/new_relic/agent/http_clients/abstract.rb
+++ b/lib/new_relic/agent/http_clients/abstract.rb
@@ -5,8 +5,8 @@
module NewRelic
module Agent
module HTTPClients
- MUST_IMPLEMENT_ERROR = "Subclasses of %s must implement a :%s method"
- WHINY_NIL_ERROR = "%s cannot initialize with a nil wrapped_response object."
+ MUST_IMPLEMENT_ERROR = 'Subclasses of %s must implement a :%s method'
+ WHINY_NIL_ERROR = '%s cannot initialize with a nil wrapped_response object.'
# This class provides a public interface for wrapping HTTP requests. This
# may be used to create wrappers that are compatible with New Relic's
@@ -14,28 +14,16 @@ module HTTPClients
#
# @api public
class AbstractRequest
- def []
- raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__]
- end
-
- def []=
- raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__]
- end
-
- def type
- raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__]
- end
-
- def host_from_header
- raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__]
+ %i[[] []= type host_from_header host method headers uri].each do |name|
+ define_method(name) do
+ not_implemented(name)
+ end
end
- def host
- raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__]
- end
+ private
- def method
- raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__]
+ def not_implemented(method_name)
+ raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, method_name]
end
end
diff --git a/lib/new_relic/agent/http_clients/curb_wrappers.rb b/lib/new_relic/agent/http_clients/curb_wrappers.rb
index c5e829c0a3..6e0fca5b00 100644
--- a/lib/new_relic/agent/http_clients/curb_wrappers.rb
+++ b/lib/new_relic/agent/http_clients/curb_wrappers.rb
@@ -33,16 +33,20 @@ def method
end
def [](key)
- @curlobj.headers[key]
+ headers[key]
end
def []=(key, value)
- @curlobj.headers[key] = value
+ headers[key] = value
end
def uri
@uri ||= URIUtil.parse_and_normalize_url(@curlobj.url)
end
+
+ def headers
+ @curlobj.headers
+ end
end
class CurbResponse < AbstractResponse
@@ -62,7 +66,7 @@ def to_hash
def append_header_data(data)
key, value = data.split(/:\s*/, 2)
@headers[key.downcase] = value
- @wrapped_response._nr_header_str ||= String.new
+ @wrapped_response._nr_header_str ||= +''
@wrapped_response._nr_header_str << data
end
diff --git a/lib/new_relic/agent/http_clients/excon_wrappers.rb b/lib/new_relic/agent/http_clients/excon_wrappers.rb
index ce65a5fcb3..13e3b51630 100644
--- a/lib/new_relic/agent/http_clients/excon_wrappers.rb
+++ b/lib/new_relic/agent/http_clients/excon_wrappers.rb
@@ -46,7 +46,7 @@ def get_status_code
class ExconHTTPRequest < AbstractRequest
attr_reader :method
- EXCON = "Excon"
+ EXCON = 'Excon'
LHOST = 'host'
UHOST = 'Host'
COLON = ':'
@@ -65,7 +65,6 @@ def type
end
def host_from_header
- headers = @datum[:headers]
if hostname = (headers[LHOST] || headers[UHOST])
hostname.split(COLON).first
end
@@ -76,18 +75,21 @@ def host
end
def [](key)
- @datum[:headers][key]
+ headers[key]
end
def []=(key, value)
- @datum[:headers] ||= {}
- @datum[:headers][key] = value
+ headers[key] = value
end
def uri
url = "#{@scheme}://#{host}:#{@port}#{@path}"
URIUtil.parse_and_normalize_url(url)
end
+
+ def headers
+ @datum[:headers]
+ end
end
end
end
diff --git a/lib/new_relic/agent/http_clients/http_rb_wrappers.rb b/lib/new_relic/agent/http_clients/http_rb_wrappers.rb
index 5ad7d6fa43..b0b041523d 100644
--- a/lib/new_relic/agent/http_clients/http_rb_wrappers.rb
+++ b/lib/new_relic/agent/http_clients/http_rb_wrappers.rb
@@ -56,6 +56,10 @@ def [](key)
def []=(key, value)
@wrapped_request.headers[key] = value
end
+
+ def headers
+ @wrapped_request.headers.to_hash
+ end
end
end
end
diff --git a/lib/new_relic/agent/http_clients/httpclient_wrappers.rb b/lib/new_relic/agent/http_clients/httpclient_wrappers.rb
index 578df4758c..88578b83d2 100644
--- a/lib/new_relic/agent/http_clients/httpclient_wrappers.rb
+++ b/lib/new_relic/agent/http_clients/httpclient_wrappers.rb
@@ -25,7 +25,7 @@ def to_hash
class HTTPClientRequest < AbstractRequest
attr_reader :request
- HTTP_CLIENT = "HTTPClient".freeze
+ HTTP_CLIENT = 'HTTPClient'.freeze
LHOST = 'host'.freeze
UHOST = 'Host'.freeze
COLON = ':'.freeze
@@ -57,12 +57,16 @@ def uri
end
def [](key)
- request.headers[key]
+ headers[key]
end
def []=(key, value)
request.http_header[key] = value
end
+
+ def headers
+ request.headers
+ end
end
end
end
diff --git a/lib/new_relic/agent/http_clients/net_http_wrappers.rb b/lib/new_relic/agent/http_clients/net_http_wrappers.rb
index ecf46ebbcd..fa4bb5c122 100644
--- a/lib/new_relic/agent/http_clients/net_http_wrappers.rb
+++ b/lib/new_relic/agent/http_clients/net_http_wrappers.rb
@@ -61,7 +61,7 @@ def uri
::NewRelic::Agent::HTTPClients::URIUtil.parse_and_normalize_url(@request.path)
else
connection_address = @connection.address
- if connection_address =~ Resolv::IPv6::Regex
+ if Resolv::IPv6::Regex.match?(connection_address)
connection_address = "[#{connection_address}]"
end
@@ -71,6 +71,10 @@ def uri
)
end
end
+
+ def headers
+ @request.instance_variable_get(:@header)
+ end
end
end
end
diff --git a/lib/new_relic/agent/http_clients/typhoeus_wrappers.rb b/lib/new_relic/agent/http_clients/typhoeus_wrappers.rb
index c98b06fd20..767edada17 100644
--- a/lib/new_relic/agent/http_clients/typhoeus_wrappers.rb
+++ b/lib/new_relic/agent/http_clients/typhoeus_wrappers.rb
@@ -42,7 +42,7 @@ def initialize(request)
end
end
- TYPHOEUS = "Typhoeus".freeze
+ TYPHOEUS = 'Typhoeus'.freeze
def type
TYPHOEUS
@@ -66,14 +66,17 @@ def method
end
def [](key)
- return nil unless @request.options && @request.options[:headers]
+ return nil unless @request.options && headers
- @request.options[:headers][key]
+ headers[key]
end
def []=(key, value)
- @request.options[:headers] ||= {}
- @request.options[:headers][key] = value
+ headers[key] = value
+ end
+
+ def headers
+ @request.options[:headers] || {}
end
def uri
diff --git a/lib/new_relic/agent/http_clients/uri_util.rb b/lib/new_relic/agent/http_clients/uri_util.rb
index bea870d9f4..f2f188bada 100644
--- a/lib/new_relic/agent/http_clients/uri_util.rb
+++ b/lib/new_relic/agent/http_clients/uri_util.rb
@@ -36,11 +36,11 @@ def self.parse_and_normalize_url(url)
uri = ::URI.parse(url)
end
end
- uri.host.downcase! unless uri.host.nil?
+ uri.host&.downcase!
uri
end
- QUESTION_MARK = "?"
+ QUESTION_MARK = '?'
def self.strip_query_string(fragment)
if fragment.include?(QUESTION_MARK)
diff --git a/lib/new_relic/agent/instrumentation/action_controller_other_subscriber.rb b/lib/new_relic/agent/instrumentation/action_controller_other_subscriber.rb
index 5b9ea78216..b6b0680ed3 100644
--- a/lib/new_relic/agent/instrumentation/action_controller_other_subscriber.rb
+++ b/lib/new_relic/agent/instrumentation/action_controller_other_subscriber.rb
@@ -27,11 +27,14 @@ def metric_name(name, payload)
end
def controller_name_for_metric(payload)
+ return unless payload
# redirect_to
- return payload[:request].controller_class.controller_path if payload[:request] && payload[:request].controller_class
+ return payload[:request].controller_class.controller_path if payload[:request].respond_to?(:controller_class) && payload[:request].controller_class&.respond_to?(:controller_path)
# unpermitted_parameters
- ::NewRelic::LanguageSupport.constantize(payload[:context][:controller]).controller_path if payload[:context] && payload[:context][:controller]
+ if payload[:context]&.[](:controller) && constantized_class = ::NewRelic::LanguageSupport.constantize(payload[:context][:controller])
+ constantized_class.respond_to?(:controller_path) ? constantized_class.controller_path : nil
+ end
end
end
end
diff --git a/lib/new_relic/agent/instrumentation/action_controller_subscriber.rb b/lib/new_relic/agent/instrumentation/action_controller_subscriber.rb
index d8c58cb7d9..62c567e274 100644
--- a/lib/new_relic/agent/instrumentation/action_controller_subscriber.rb
+++ b/lib/new_relic/agent/instrumentation/action_controller_subscriber.rb
@@ -19,7 +19,7 @@ def start(name, id, payload) # THREAD_LOCAL_ACCESS
else
# if this transaction is ignored, make sure child
# transaction are also ignored
- state.current_transaction.ignore! if state.current_transaction
+ state.current_transaction&.ignore!
NewRelic::Agent.instance.push_trace_execution_flag(false)
end
rescue => e
@@ -90,7 +90,8 @@ def should_ignore(payload, controller_class)
end
def queue_start(request)
- if request && request.respond_to?(:env)
+ # the following line needs else branch coverage
+ if request && request.respond_to?(:env) # rubocop:disable Style/SafeNavigation
QueueTime.parse_frontend_timestamp(request.env, Process.clock_gettime(Process::CLOCK_REALTIME))
end
end
diff --git a/lib/new_relic/agent/instrumentation/action_view_subscriber.rb b/lib/new_relic/agent/instrumentation/action_view_subscriber.rb
index 6aa9747fdc..adcd969a00 100644
--- a/lib/new_relic/agent/instrumentation/action_view_subscriber.rb
+++ b/lib/new_relic/agent/instrumentation/action_view_subscriber.rb
@@ -75,7 +75,7 @@ def metric_path(name, identifier)
# so do not mistake rendering a collection for rendering a file.
if identifier.nil? && name != RENDER_COLLECTION_EVENT_NAME
'file'
- elsif identifier =~ /template$/
+ elsif /template$/.match?(identifier)
identifier
elsif identifier && (parts = identifier.split('/')).size > 1
parts[-2..-1].join('/')
@@ -99,11 +99,11 @@ def initialize(name, identifier)
end
def finish
- @finishable.finish if @finishable
+ @finishable&.finish
end
def notice_error(error)
- @finishable.notice_error(error) if @finishable
+ @finishable&.notice_error(error)
end
end
end
diff --git a/lib/new_relic/agent/instrumentation/active_job.rb b/lib/new_relic/agent/instrumentation/active_job.rb
index b44fc5d330..650649ac63 100644
--- a/lib/new_relic/agent/instrumentation/active_job.rb
+++ b/lib/new_relic/agent/instrumentation/active_job.rb
@@ -57,7 +57,7 @@ def self.perform(job, block)
# Don't nest transactions if we're already in a web transaction.
# Probably inline processing the job if that happens, so just trace.
- if txn && txn.recording_web_transaction?
+ if txn&.recording_web_transaction?
run_in_trace(job, block, :Consume)
elsif txn && !txn.recording_web_transaction?
::NewRelic::Agent::Transaction.set_default_transaction_name(
diff --git a/lib/new_relic/agent/instrumentation/active_record.rb b/lib/new_relic/agent/instrumentation/active_record.rb
index e7f666421d..8cdcdcbcd2 100644
--- a/lib/new_relic/agent/instrumentation/active_record.rb
+++ b/lib/new_relic/agent/instrumentation/active_record.rb
@@ -13,7 +13,8 @@ module ActiveRecord
::ActiveRecord::Base.send("#{statement.config[:adapter]}_connection",
statement.config)
end
- if connection && connection.respond_to?(:execute)
+ # the following line needs else branch coverage
+ if connection && connection.respond_to?(:execute) # rubocop:disable Style/SafeNavigation
return connection.execute("EXPLAIN #{statement.sql}")
end
end
@@ -43,7 +44,7 @@ def self.included(instrumented_class)
end
end
- if RUBY_VERSION < "2.7.0"
+ if RUBY_VERSION < '2.7.0'
def log_with_newrelic_instrumentation(*args, &block)
state = NewRelic::Agent::Tracer.state
diff --git a/lib/new_relic/agent/instrumentation/active_record_helper.rb b/lib/new_relic/agent/instrumentation/active_record_helper.rb
index 0798db5eb0..4fb323004d 100644
--- a/lib/new_relic/agent/instrumentation/active_record_helper.rb
+++ b/lib/new_relic/agent/instrumentation/active_record_helper.rb
@@ -49,7 +49,7 @@ def update_all(*args, &blk)
alias_method(:delete_all_without_newrelic, :delete_all)
- if RUBY_VERSION < "2.7.0"
+ if RUBY_VERSION < '2.7.0'
def delete_all(*args, &blk)
::NewRelic::Agent.with_database_metric_name(self.name, nil, ACTIVE_RECORD) do
delete_all_without_newrelic(*args, &blk)
@@ -92,9 +92,9 @@ def pluck(*args, &blk)
end
end
- ACTIVE_RECORD = "ActiveRecord".freeze
- OTHER = "other".freeze
- MAKARA_SUFFIX = "_makara".freeze
+ ACTIVE_RECORD = 'ActiveRecord'.freeze
+ OTHER = 'other'.freeze
+ MAKARA_SUFFIX = '_makara'.freeze
# convert vendor (makara, etc.) wrapper names to their bare names
# ex: postgresql_makara -> postgresql
@@ -102,7 +102,7 @@ def bare_adapter_name(adapter_name)
# TODO: OLD RUBIES - RUBY_VERSION < 2.5
# With Ruby 2.5+ we could use #delete_suffix instead of #chomp for a
# potential speed boost
- return adapter_name.chomp(MAKARA_SUFFIX) if adapter_name && adapter_name.end_with?(MAKARA_SUFFIX)
+ return adapter_name.chomp(MAKARA_SUFFIX) if adapter_name&.end_with?(MAKARA_SUFFIX)
adapter_name
end
@@ -118,7 +118,7 @@ def product_operation_collection_for(name, sql, adapter_name)
SPACE = ' '.freeze
def split_name(name)
- if name && name.respond_to?(:split)
+ if name&.respond_to?(:split)
name.split(SPACE)
else
NewRelic::EMPTY_ARRAY
@@ -163,47 +163,50 @@ def map_operation(raw_operation)
end
PRODUCT_NAMES = {
- "mysql" => "MySQL",
- "mysql2" => "MySQL",
+ 'mysql' => 'MySQL',
+ 'mysql2' => 'MySQL',
- "postgresql" => "Postgres",
+ 'postgresql' => 'Postgres',
- "sqlite3" => "SQLite",
+ 'sqlite3' => 'SQLite',
# https://rubygems.org/gems/activerecord-jdbcpostgresql-adapter
- "jdbcmysql" => "MySQL",
+ 'jdbcmysql' => 'MySQL',
# https://rubygems.org/gems/activerecord-jdbcpostgresql-adapter
- "jdbcpostgresql" => "Postgres",
+ 'jdbcpostgresql' => 'Postgres',
# https://rubygems.org/gems/activerecord-postgis-adapter
- "postgis" => "Postgres",
+ 'postgis' => 'Postgres',
# https://rubygems.org/gems/activerecord-jdbcsqlite3-adapter
- "jdbcsqlite3" => "SQLite",
+ 'jdbcsqlite3' => 'SQLite',
# https://rubygems.org/gems/activerecord-jdbcderby-adapter
- "derby" => "Derby",
- "jdbcderby" => "Derby",
+ 'derby' => 'Derby',
+ 'jdbcderby' => 'Derby',
# https://rubygems.org/gems/activerecord-jdbc-adapter
- "jdbc" => "JDBC",
+ 'jdbc' => 'JDBC',
# https://rubygems.org/gems/activerecord-jdbcmssql-adapter
- "jdbcmssql" => "MSSQL",
- "mssql" => "MSSQL",
+ 'jdbcmssql' => 'MSSQL',
+ 'mssql' => 'MSSQL',
# https://rubygems.org/gems/activerecord-sqlserver-adapter
- "sqlserver" => "MSSQL",
+ 'sqlserver' => 'MSSQL',
# https://rubygems.org/gems/activerecord-odbc-adapter
- "odbc" => "ODBC",
+ 'odbc' => 'ODBC',
# https://rubygems.org/gems/activerecord-oracle_enhanced-adapter
- "oracle_enhanced" => "Oracle"
+ 'oracle_enhanced' => 'Oracle',
+
+ # https://rubygems.org/gems/activerecord-amazon-timestream-adapter
+ 'amazon_timestream' => 'Timestream'
}.freeze
- ACTIVE_RECORD_DEFAULT_PRODUCT_NAME = "ActiveRecord".freeze
+ ACTIVE_RECORD_DEFAULT_PRODUCT_NAME = 'ActiveRecord'.freeze
def map_product(adapter_name)
PRODUCT_NAMES.fetch(adapter_name, ACTIVE_RECORD_DEFAULT_PRODUCT_NAME)
@@ -213,24 +216,24 @@ module InstanceIdentification
extend self
PRODUCT_SYMBOLS = {
- "mysql" => :mysql,
- "mysql2" => :mysql,
- "jdbcmysql" => :mysql,
+ 'mysql' => :mysql,
+ 'mysql2' => :mysql,
+ 'jdbcmysql' => :mysql,
- "postgresql" => :postgres,
- "jdbcpostgresql" => :postgres,
- "postgis" => :postgres
+ 'postgresql' => :postgres,
+ 'jdbcpostgresql' => :postgres,
+ 'postgis' => :postgres
}.freeze
DATASTORE_DEFAULT_PORTS = {
- :mysql => "3306",
- :postgres => "5432"
+ :mysql => '3306',
+ :postgres => '5432'
}.freeze
- DEFAULT = "default".freeze
- UNKNOWN = "unknown".freeze
- SLASH = "/".freeze
- LOCALHOST = "localhost".freeze
+ DEFAULT = 'default'.freeze
+ UNKNOWN = 'unknown'.freeze
+ SLASH = '/'.freeze
+ LOCALHOST = 'localhost'.freeze
def adapter_from_config(config)
bare_name = NewRelic::Agent::Instrumentation::ActiveRecordHelper.bare_adapter_name(config[:adapter])
diff --git a/lib/new_relic/agent/instrumentation/active_record_notifications.rb b/lib/new_relic/agent/instrumentation/active_record_notifications.rb
index 1e33ba89f8..84296d147f 100644
--- a/lib/new_relic/agent/instrumentation/active_record_notifications.rb
+++ b/lib/new_relic/agent/instrumentation/active_record_notifications.rb
@@ -16,7 +16,7 @@ module ActiveRecordNotifications
module BaseExtensions4x
# https://github.com/rails/rails/blob/4-1-stable/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb#L371
- def log(sql, name = "SQL", binds = [], statement_name = nil)
+ def log(sql, name = 'SQL', binds = [], statement_name = nil)
@instrumenter.instrument(
SQL_ACTIVE_RECORD,
:sql => sql,
@@ -38,7 +38,7 @@ def log(sql, name = "SQL", binds = [], statement_name = nil)
module BaseExtensions50
# https://github.com/rails/rails/blob/5-0-stable/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb#L582
- def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil)
+ def log(sql, name = 'SQL', binds = [], type_casted_binds = [], statement_name = nil)
@instrumenter.instrument(
SQL_ACTIVE_RECORD,
sql: sql,
@@ -56,7 +56,7 @@ def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name =
module BaseExtensions51
# https://github.com/rails/rails/blob/5-1-stable/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb#L603
- def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil) # :doc:
+ def log(sql, name = 'SQL', binds = [], type_casted_binds = [], statement_name = nil) # :doc:
@instrumenter.instrument(
SQL_ACTIVE_RECORD,
sql: sql,
diff --git a/lib/new_relic/agent/instrumentation/active_record_prepend.rb b/lib/new_relic/agent/instrumentation/active_record_prepend.rb
index 7fb126cb2f..376bb1adb2 100644
--- a/lib/new_relic/agent/instrumentation/active_record_prepend.rb
+++ b/lib/new_relic/agent/instrumentation/active_record_prepend.rb
@@ -11,7 +11,7 @@ module ActiveRecordPrepend
ACTIVE_RECORD = 'ActiveRecord'.freeze
module BaseExtensions
- if RUBY_VERSION < "2.7.0"
+ if RUBY_VERSION < '2.7.0'
def save(*args, &blk)
::NewRelic::Agent.with_database_metric_name(self.class.name, nil, ACTIVE_RECORD) do
super
@@ -46,7 +46,7 @@ module BaseExtensions516
# Starting in v5.1.6, this call no longer happens. We'll
# have to set the database metrics explicitly now.
#
- if RUBY_VERSION < "2.7.0"
+ if RUBY_VERSION < '2.7.0'
def touch(*args, **kwargs, &blk)
::NewRelic::Agent.with_database_metric_name(self.class.name, nil, ACTIVE_RECORD) do
super
diff --git a/lib/new_relic/agent/instrumentation/active_record_subscriber.rb b/lib/new_relic/agent/instrumentation/active_record_subscriber.rb
index dd54ef50b7..92c11e3e9f 100644
--- a/lib/new_relic/agent/instrumentation/active_record_subscriber.rb
+++ b/lib/new_relic/agent/instrumentation/active_record_subscriber.rb
@@ -33,7 +33,7 @@ def define_cachedp_method
# defensive.
return if defined?(cached?)
- if defined?(::ActiveRecord) && ::ActiveRecord::VERSION::STRING >= "5.1.0"
+ if defined?(::ActiveRecord) && ::ActiveRecord::VERSION::STRING >= '5.1.0'
def cached?(payload)
payload.fetch(:cached, false)
end
@@ -74,7 +74,8 @@ def get_explain_plan(statement)
::ActiveRecord::Base.send("#{statement.config[:adapter]}_connection",
statement.config)
end
- if connection && connection.respond_to?(:exec_query)
+ # the following line needs else branch coverage
+ if connection && connection.respond_to?(:exec_query) # rubocop:disable Style/SafeNavigation
return connection.exec_query("EXPLAIN #{statement.sql}",
"Explain #{statement.name}",
statement.binds)
diff --git a/lib/new_relic/agent/instrumentation/bunny/instrumentation.rb b/lib/new_relic/agent/instrumentation/bunny/instrumentation.rb
index 3e52829dbe..ea3a5af4ba 100644
--- a/lib/new_relic/agent/instrumentation/bunny/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/bunny/instrumentation.rb
@@ -46,7 +46,7 @@ def publish_with_tracing(payload, opts = {})
exchange_type: type
)
rescue => e
- NewRelic::Agent.logger.error("Error starting message broker segment in Bunny::Exchange#publish", e)
+ NewRelic::Agent.logger.error('Error starting message broker segment in Bunny::Exchange#publish', e)
yield
else
NewRelic::Agent::Tracer.capture_segment_error(segment) do
@@ -90,7 +90,7 @@ def pop_with_tracing
start_time: t0
)
rescue => e
- NewRelic::Agent.logger.error("Error starting message broker segment in Bunny::Queue#pop", e)
+ NewRelic::Agent.logger.error('Error starting message broker segment in Bunny::Queue#pop', e)
else
if bunny_error
segment.notice_error(bunny_error)
@@ -113,7 +113,7 @@ def purge_with_tracing
destination_name: name
)
rescue => e
- NewRelic::Agent.logger.error("Error starting message broker segment in Bunny::Queue#purge", e)
+ NewRelic::Agent.logger.error('Error starting message broker segment in Bunny::Queue#purge', e)
yield
else
NewRelic::Agent::Tracer.capture_segment_error(segment) do
diff --git a/lib/new_relic/agent/instrumentation/controller_instrumentation.rb b/lib/new_relic/agent/instrumentation/controller_instrumentation.rb
index fad7eca092..90e77bdc5d 100644
--- a/lib/new_relic/agent/instrumentation/controller_instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/controller_instrumentation.rb
@@ -236,7 +236,8 @@ def self.name_for(txn, traced_obj, category, options = {})
end
def self.prefix_for_category(txn, category = nil)
- category ||= (txn && txn.category)
+ # the following line needs else branch coverage
+ category ||= (txn && txn.category) # rubocop:disable Style/SafeNavigation
case category
when :controller then ::NewRelic::Agent::Transaction::CONTROLLER_PREFIX
when :web then ::NewRelic::Agent::Transaction::CONTROLLER_PREFIX
@@ -360,7 +361,7 @@ def perform_action_with_newrelic_trace(*args, &block) # THREAD_LOCAL_ACCESS
skip_tracing = do_not_trace? || !state.is_execution_traced?
if skip_tracing
- state.current_transaction.ignore! if state.current_transaction
+ state.current_transaction&.ignore!
NewRelic::Agent.disable_all_tracing { return yield }
end
@@ -386,7 +387,8 @@ def perform_action_with_newrelic_trace(*args, &block) # THREAD_LOCAL_ACCESS
raise
end
ensure
- finishable.finish if finishable
+ # the following line needs else branch coverage
+ finishable.finish if finishable # rubocop:disable Style/SafeNavigation
end
end
diff --git a/lib/new_relic/agent/instrumentation/curb.rb b/lib/new_relic/agent/instrumentation/curb.rb
index 8fdc276ad3..2aa2699e67 100644
--- a/lib/new_relic/agent/instrumentation/curb.rb
+++ b/lib/new_relic/agent/instrumentation/curb.rb
@@ -8,7 +8,7 @@
DependencyDetection.defer do
named :curb
- CURB_MIN_VERSION = Gem::Version.new("0.8.1")
+ CURB_MIN_VERSION = Gem::Version.new('0.8.1')
depends_on do
defined?(Curl) && defined?(Curl::CURB_VERSION) &&
diff --git a/lib/new_relic/agent/instrumentation/curb/chain.rb b/lib/new_relic/agent/instrumentation/curb/chain.rb
index 2c6dc80244..dc85bda3a3 100644
--- a/lib/new_relic/agent/instrumentation/curb/chain.rb
+++ b/lib/new_relic/agent/instrumentation/curb/chain.rb
@@ -7,7 +7,7 @@
module NewRelic::Agent::Instrumentation
module Curb
module Chain
- def self.instrument!
+ def self.instrument! # rubocop:disable Metrics/AbcSize
Curl::Easy.class_eval do
include NewRelic::Agent::Instrumentation::Curb::Easy
diff --git a/lib/new_relic/agent/instrumentation/curb/instrumentation.rb b/lib/new_relic/agent/instrumentation/curb/instrumentation.rb
index 3ad3fb5b98..43d9aca30a 100644
--- a/lib/new_relic/agent/instrumentation/curb/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/curb/instrumentation.rb
@@ -81,7 +81,7 @@ def add_with_tracing(curl)
def perform_with_tracing
return yield if first_request_is_serial?
- trace_execution_scoped("External/Multiple/Curb::Multi/perform") do
+ trace_execution_scoped('External/Multiple/Curb::Multi/perform') do
yield
end
end
@@ -107,7 +107,7 @@ def hook_pending_request(request)
request._nr_instrumented = true
end
rescue => err
- NewRelic::Agent.logger.error("Untrapped exception", err)
+ NewRelic::Agent.logger.error('Untrapped exception', err)
end
# Create request and response adapter objects for the specified +request+
@@ -141,12 +141,12 @@ def install_completion_callback(request, wrapped_response, segment)
request._nr_original_on_complete = original_callback
request.on_complete do |finished_request|
begin
- segment.process_response_headers(wrapped_response) if segment
+ segment&.process_response_headers(wrapped_response)
ensure
::NewRelic::Agent::Transaction::Segment.finish(segment)
# Make sure the existing completion callback is run, and restore the
# on_complete callback to how it was before.
- original_callback.call(finished_request) if original_callback
+ original_callback&.call(finished_request)
remove_instrumentation_callbacks(request)
end
end
@@ -173,7 +173,7 @@ def install_failure_callback(request, _wrapped_response, segment)
segment.notice_error(noticeable_error)
end
ensure
- original_callback.call(failed_request, error) if original_callback
+ original_callback&.call(failed_request, error)
remove_failure_callback(failed_request)
end
end
diff --git a/lib/new_relic/agent/instrumentation/custom_events_subscriber.rb b/lib/new_relic/agent/instrumentation/custom_events_subscriber.rb
index b94b5a5efc..b45fd86a5a 100644
--- a/lib/new_relic/agent/instrumentation/custom_events_subscriber.rb
+++ b/lib/new_relic/agent/instrumentation/custom_events_subscriber.rb
@@ -23,7 +23,8 @@ def finish(name, id, payload) # THREAD_LOCAL_ACCESS
NewRelic::Agent.notice_error(payload[:exception_object]) if payload.key?(:exception_object)
finishable = pop_segment(id)
- finishable.finish if finishable
+ # the following line needs else branch coverage
+ finishable.finish if finishable # rubocop:disable Style/SafeNavigation
rescue => e
log_notification_error(e, name, 'finish')
end
diff --git a/lib/new_relic/agent/instrumentation/delayed_job/instrumentation.rb b/lib/new_relic/agent/instrumentation/delayed_job/instrumentation.rb
index f6e5acea23..8661938384 100644
--- a/lib/new_relic/agent/instrumentation/delayed_job/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/delayed_job/instrumentation.rb
@@ -22,7 +22,7 @@ def initialize_with_tracing
install_newrelic_job_tracer
NewRelic::Control.instance.init_plugin(:dispatcher => :delayed_job)
else
- NewRelic::Agent.logger.warn("Did not find a Delayed::Job class responding to invoke_job, aborting DJ instrumentation")
+ NewRelic::Agent.logger.warn('Did not find a Delayed::Job class responding to invoke_job, aborting DJ instrumentation')
end
end
end
diff --git a/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb b/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb
index 59ad6ea76f..f725821be5 100644
--- a/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb
@@ -109,6 +109,7 @@ def method_name(payload_object)
end
def delayed_job_version
- Gem.loaded_specs['delayed_job'].version if Gem.loaded_specs['delayed_job']
+ # the following line needs else branch coverage
+ Gem.loaded_specs['delayed_job'].version if Gem.loaded_specs['delayed_job'] # rubocop:disable Style/SafeNavigation
end
end
diff --git a/lib/new_relic/agent/instrumentation/elasticsearch.rb b/lib/new_relic/agent/instrumentation/elasticsearch.rb
index 423a9b9f9b..8493d21e9d 100644
--- a/lib/new_relic/agent/instrumentation/elasticsearch.rb
+++ b/lib/new_relic/agent/instrumentation/elasticsearch.rb
@@ -16,7 +16,7 @@
executes do
NewRelic::Agent.logger.info('Installing Elasticsearch instrumentation')
- to_instrument = if Gem::Version.create(Elasticsearch::VERSION) < Gem::Version.create("8.0.0")
+ to_instrument = if Gem::Version.create(Elasticsearch::VERSION) < Gem::Version.create('8.0.0')
Elasticsearch::Transport::Client
else
Elastic::Transport::Client
diff --git a/lib/new_relic/agent/instrumentation/elasticsearch/chain.rb b/lib/new_relic/agent/instrumentation/elasticsearch/chain.rb
index b88ce20e5d..00242a8ca4 100644
--- a/lib/new_relic/agent/instrumentation/elasticsearch/chain.rb
+++ b/lib/new_relic/agent/instrumentation/elasticsearch/chain.rb
@@ -6,7 +6,7 @@ module NewRelic::Agent::Instrumentation
module Elasticsearch
def self.instrument!
to_instrument = if ::Gem::Version.create(::Elasticsearch::VERSION) <
- ::Gem::Version.create("8.0.0")
+ ::Gem::Version.create('8.0.0')
::Elasticsearch::Transport::Client
else
::Elastic::Transport::Client
diff --git a/lib/new_relic/agent/instrumentation/elasticsearch/instrumentation.rb b/lib/new_relic/agent/instrumentation/elasticsearch/instrumentation.rb
index 7bca0c1d45..2b92ddbc1d 100644
--- a/lib/new_relic/agent/instrumentation/elasticsearch/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/elasticsearch/instrumentation.rb
@@ -37,7 +37,7 @@ def nr_operation
end
return nil unless operation_index
- caller_locations[operation_index].to_s.split('`')[-1].gsub(/\W/, "")
+ caller_locations[operation_index].to_s.split('`')[-1].gsub(/\W/, '')
end
def nr_reported_query(query)
@@ -52,10 +52,10 @@ def nr_cluster_name
return if nr_hosts.empty?
NewRelic::Agent.disable_all_tracing do
- @nr_cluster_name ||= perform_request('GET', '_cluster/health').body["cluster_name"]
+ @nr_cluster_name ||= perform_request('GET', '_cluster/health').body['cluster_name']
end
rescue StandardError => e
- NewRelic::Agent.logger.error("Failed to get cluster name for elasticsearch", e)
+ NewRelic::Agent.logger.error('Failed to get cluster name for elasticsearch', e)
nil
end
diff --git a/lib/new_relic/agent/instrumentation/excon.rb b/lib/new_relic/agent/instrumentation/excon.rb
index 9203027c48..949920b767 100644
--- a/lib/new_relic/agent/instrumentation/excon.rb
+++ b/lib/new_relic/agent/instrumentation/excon.rb
@@ -18,7 +18,7 @@
# but alas, it does not yet.
# TODO: MAJOR VERSION - update min version to 0.56.0
- EXCON_MIN_VERSION = Gem::Version.new("0.19.0")
+ EXCON_MIN_VERSION = Gem::Version.new('0.19.0')
depends_on do
defined?(Excon) && defined?(Excon::VERSION)
@@ -46,7 +46,7 @@
deprecation_msg
)
- NewRelic::Agent.record_metric("Supportability/Deprecated/Excon", 1)
+ NewRelic::Agent.record_metric('Supportability/Deprecated/Excon', 1)
end
def install_excon_instrumentation(excon_version)
@@ -64,7 +64,7 @@ def install_middleware_excon_instrumentation
if defaults[:middlewares]
defaults[:middlewares] << Excon::Middleware::NewRelicCrossAppTracing
else
- NewRelic::Agent.logger.warn("Did not find :middlewares key in Excon.defaults, skipping Excon instrumentation")
+ NewRelic::Agent.logger.warn('Did not find :middlewares key in Excon.defaults, skipping Excon instrumentation')
end
end
end
diff --git a/lib/new_relic/agent/instrumentation/excon/middleware.rb b/lib/new_relic/agent/instrumentation/excon/middleware.rb
index a4cb48e042..82bb4397ba 100644
--- a/lib/new_relic/agent/instrumentation/excon/middleware.rb
+++ b/lib/new_relic/agent/instrumentation/excon/middleware.rb
@@ -46,7 +46,8 @@ def error_call(datum)
end
def finish_trace(datum) # THREAD_LOCAL_ACCESS
- segment = datum[:connection] && datum[:connection].instance_variable_get(TRACE_DATA_IVAR)
+ # The following line needs else branch coverage
+ segment = datum[:connection] && datum[:connection].instance_variable_get(TRACE_DATA_IVAR) # rubocop:disable Style/SafeNavigation
if segment
begin
segment.notice_error(datum[:error]) if datum[:error]
diff --git a/lib/new_relic/agent/instrumentation/grape.rb b/lib/new_relic/agent/instrumentation/grape.rb
index e5624390ba..26198326d0 100644
--- a/lib/new_relic/agent/instrumentation/grape.rb
+++ b/lib/new_relic/agent/instrumentation/grape.rb
@@ -19,14 +19,14 @@
depends_on do
begin
- if defined?(Bundler) && Bundler.rubygems.all_specs.map(&:name).include?("newrelic-grape")
- NewRelic::Agent.logger.info("Not installing New Relic supported Grape instrumentation because the third party newrelic-grape gem is present")
+ if defined?(Bundler) && Bundler.rubygems.all_specs.map(&:name).include?('newrelic-grape')
+ NewRelic::Agent.logger.info('Not installing New Relic supported Grape instrumentation because the third party newrelic-grape gem is present')
false
else
true
end
rescue => e
- NewRelic::Agent.logger.info("Could not determine if third party newrelic-grape gem is installed", e)
+ NewRelic::Agent.logger.info('Could not determine if third party newrelic-grape gem is installed', e)
true
end
end
diff --git a/lib/new_relic/agent/instrumentation/grape/instrumentation.rb b/lib/new_relic/agent/instrumentation/grape/instrumentation.rb
index 8f900c1002..1e7ad1eb08 100644
--- a/lib/new_relic/agent/instrumentation/grape/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/grape/instrumentation.rb
@@ -23,12 +23,12 @@ def capture_transaction(env, context)
api_class = (context.class.respond_to?(:base) && context.class.base) || context.class
handle_transaction(endpoint, api_class.name, version)
rescue => e
- ::NewRelic::Agent.logger.warn("Error in Grape instrumentation", e)
+ ::NewRelic::Agent.logger.warn('Error in Grape instrumentation', e)
end
end
def prepare!
- if defined?(::Grape::VERSION) && Gem::Version.new(::Grape::VERSION) >= Gem::Version.new("0.16.0")
+ if defined?(::Grape::VERSION) && Gem::Version.new(::Grape::VERSION) >= Gem::Version.new('0.16.0')
send(:remove_method, :name_for_transaction_deprecated)
else
send(:remove_method, :name_for_transaction)
@@ -40,7 +40,7 @@ def prepare!
API_VERSION = 'api.version'.freeze
FORMAT_REGEX = /\(\/?\.[\:\w]*\)/.freeze # either :format (< 0.12.0) or .ext (>= 0.12.0)
VERSION_REGEX = /:version(\/|$)/.freeze
- MIN_VERSION = Gem::Version.new("0.2.0")
+ MIN_VERSION = Gem::Version.new('0.2.0')
PIPE_STRING = '|'.freeze
def handle_transaction(endpoint, class_name, version)
@@ -91,7 +91,7 @@ def capture_params(endpoint)
txn = ::NewRelic::Agent::Transaction.tl_current
env = endpoint.request.env
params = ::NewRelic::Agent::ParameterFiltering::apply_filters(env, endpoint.params)
- params.delete("route_info")
+ params.delete('route_info')
txn.filtered_params = params
txn.merge_request_parameters(params)
end
diff --git a/lib/new_relic/agent/instrumentation/grpc/client/instrumentation.rb b/lib/new_relic/agent/instrumentation/grpc/client/instrumentation.rb
index 1a9be33b1c..c3cbc5a8c6 100644
--- a/lib/new_relic/agent/instrumentation/grpc/client/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/grpc/client/instrumentation.rb
@@ -18,7 +18,8 @@ def issue_request_with_tracing(grpc_type, method, requests, marshal, unmarshal,
segment = request_segment(method)
request_wrapper = NewRelic::Agent::Instrumentation::GRPC::Client::RequestWrapper.new(@host)
- segment.add_request_headers(request_wrapper)
+ # do not insert CAT headers for gRPC requests https://github.com/newrelic/newrelic-ruby-agent/issues/1730
+ segment.add_request_headers(request_wrapper) unless CrossAppTracing.cross_app_enabled?
metadata.merge!(request_wrapper.instance_variable_get(:@newrelic_metadata))
grpc_message = nil
grpc_status = 0
diff --git a/lib/new_relic/agent/instrumentation/grpc/server/instrumentation.rb b/lib/new_relic/agent/instrumentation/grpc/server/instrumentation.rb
index 383b214173..d8f2a3193a 100644
--- a/lib/new_relic/agent/instrumentation/grpc/server/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/grpc/server/instrumentation.rb
@@ -37,7 +37,7 @@ def handle_with_tracing(streamer_type, active_call, mth, _inter_ctx)
raise
end
ensure
- txn.finish if txn
+ txn&.finish
end
def add_http2_port_with_tracing(*args)
@@ -55,12 +55,12 @@ def run_with_tracing(*args)
def add_attributes(txn, metadata, streamer_type)
grpc_params(metadata, streamer_type).each do |attr, value|
txn.add_agent_attribute(attr, value, DESTINATIONS)
- txn.current_segment.add_agent_attribute(attr, value) if txn.current_segment
+ txn.current_segment&.add_agent_attribute(attr, value)
end
end
def metadata_for_call(active_call)
- return NewRelic::EMPTY_HASH unless active_call && active_call.metadata
+ return NewRelic::EMPTY_HASH unless active_call&.metadata
active_call.metadata
end
diff --git a/lib/new_relic/agent/instrumentation/httprb.rb b/lib/new_relic/agent/instrumentation/httprb.rb
index 6aabe5efe2..822a2b0469 100644
--- a/lib/new_relic/agent/instrumentation/httprb.rb
+++ b/lib/new_relic/agent/instrumentation/httprb.rb
@@ -14,7 +14,7 @@
end
executes do
- NewRelic::Agent.logger.info("Installing http.rb Wrappers")
+ NewRelic::Agent.logger.info('Installing http.rb Wrappers')
require 'new_relic/agent/distributed_tracing/cross_app_tracing'
require 'new_relic/agent/http_clients/http_rb_wrappers'
end
diff --git a/lib/new_relic/agent/instrumentation/ignore_actions.rb b/lib/new_relic/agent/instrumentation/ignore_actions.rb
index d776cfffbf..7c467cd4d5 100644
--- a/lib/new_relic/agent/instrumentation/ignore_actions.rb
+++ b/lib/new_relic/agent/instrumentation/ignore_actions.rb
@@ -21,7 +21,7 @@ def self.is_filtered?(key, klass, action_name)
only_actions.include?(action_name) || (!except_actions.empty? && !except_actions.include?(action_name))
else
- !!ignore_actions
+ !ignore_actions.nil?
end
return true if should_filter
diff --git a/lib/new_relic/agent/instrumentation/logger.rb b/lib/new_relic/agent/instrumentation/logger.rb
index f565bb7ccc..c351fa6f59 100644
--- a/lib/new_relic/agent/instrumentation/logger.rb
+++ b/lib/new_relic/agent/instrumentation/logger.rb
@@ -15,7 +15,7 @@
end
executes do
- NewRelic::Agent.logger.info("Installing Logger instrumentation")
+ NewRelic::Agent.logger.info('Installing Logger instrumentation')
if use_prepend?
prepend_instrument Logger, NewRelic::Agent::Instrumentation::Logger::Prepend
diff --git a/lib/new_relic/agent/instrumentation/memcache.rb b/lib/new_relic/agent/instrumentation/memcache.rb
index f61a719aa9..d761eec3ff 100644
--- a/lib/new_relic/agent/instrumentation/memcache.rb
+++ b/lib/new_relic/agent/instrumentation/memcache.rb
@@ -23,9 +23,9 @@
executes do
if use_prepend?
prepend_module = NewRelic::Agent::Instrumentation::Memcache::Prepend.client_prepender(MemCache)
- prepend_instrument MemCache, prepend_module, "MemcacheClient"
+ prepend_instrument MemCache, prepend_module, 'MemcacheClient'
else
- chain_instrument_target MemCache, NewRelic::Agent::Instrumentation::Memcache::Chain, "MemcacheClient"
+ chain_instrument_target MemCache, NewRelic::Agent::Instrumentation::Memcache::Chain, 'MemcacheClient'
end
end
end
@@ -38,9 +38,9 @@
executes do
if use_prepend?
prepend_module = NewRelic::Agent::Instrumentation::Memcache::Prepend.client_prepender(Memcached)
- prepend_instrument Memcached, prepend_module, "Memcached"
+ prepend_instrument Memcached, prepend_module, 'Memcached'
else
- chain_instrument_target Memcached, NewRelic::Agent::Instrumentation::Memcache::Chain, "Memcached"
+ chain_instrument_target Memcached, NewRelic::Agent::Instrumentation::Memcache::Chain, 'Memcached'
end
end
end
@@ -55,7 +55,7 @@
if use_prepend?
prepend_module = NewRelic::Agent::Instrumentation::Memcache::Prepend
prepend_module.dalli_prependers do |client_class, instrumenting_module|
- prepend_instrument client_class, instrumenting_module, "MemcachedDalli"
+ prepend_instrument client_class, instrumenting_module, 'MemcachedDalli'
end
else
chain_instrument NewRelic::Agent::Instrumentation::Memcache::Dalli
@@ -78,7 +78,7 @@
if use_prepend?
prepend_module = NewRelic::Agent::Instrumentation::Memcache::Prepend
prepend_module.dalli_cas_prependers do |client_class, instrumenting_module|
- prepend_instrument client_class, instrumenting_module, "MemcachedDalliCAS"
+ prepend_instrument client_class, instrumenting_module, 'MemcachedDalliCAS'
end
else
chain_instrument NewRelic::Agent::Instrumentation::Memcache::DalliCAS
diff --git a/lib/new_relic/agent/instrumentation/memcache/instrumentation.rb b/lib/new_relic/agent/instrumentation/memcache/instrumentation.rb
index 2107b40bc4..02d7d3643b 100644
--- a/lib/new_relic/agent/instrumentation/memcache/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/memcache/instrumentation.rb
@@ -8,8 +8,8 @@ module Tracer
SLASH = '/'
UNKNOWN = 'unknown'
LOCALHOST = 'localhost'
- MULTIGET_METRIC_NAME = "get_multi_request"
- MEMCACHED = "Memcached"
+ MULTIGET_METRIC_NAME = 'get_multi_request'
+ MEMCACHED = 'Memcached'
def with_newrelic_tracing(operation, *args)
segment = NewRelic::Agent::Tracer.start_datastore_segment( \
diff --git a/lib/new_relic/agent/instrumentation/middleware_proxy.rb b/lib/new_relic/agent/instrumentation/middleware_proxy.rb
index 0317a46b2b..8986c2fbde 100644
--- a/lib/new_relic/agent/instrumentation/middleware_proxy.rb
+++ b/lib/new_relic/agent/instrumentation/middleware_proxy.rb
@@ -15,8 +15,8 @@ module Instrumentation
class MiddlewareProxy
include MiddlewareTracing
- ANONYMOUS_CLASS = "AnonymousClass".freeze
- OBJECT_CLASS_NAME = "Object".freeze
+ ANONYMOUS_CLASS = 'AnonymousClass'.freeze
+ OBJECT_CLASS_NAME = 'Object'.freeze
# This class is used to wrap classes that are passed to
# Rack::Builder#use without synchronously instantiating those classes.
@@ -92,7 +92,7 @@ def determine_class_name
clazz = class_for_target
name = clazz.name
- name = clazz.superclass.name if name.nil? || name == ""
+ name = clazz.superclass.name if name.nil? || name == ''
name = ANONYMOUS_CLASS if name.nil? || name == OBJECT_CLASS_NAME
name
end
diff --git a/lib/new_relic/agent/instrumentation/middleware_tracing.rb b/lib/new_relic/agent/instrumentation/middleware_tracing.rb
index c1773f099a..9215227d54 100644
--- a/lib/new_relic/agent/instrumentation/middleware_tracing.rb
+++ b/lib/new_relic/agent/instrumentation/middleware_tracing.rb
@@ -108,7 +108,7 @@ def call(env)
NewRelic::Agent.notice_error(e)
raise e
ensure
- finishable.finish if finishable
+ finishable&.finish
end
end
diff --git a/lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb b/lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb
index 776dd0d293..4b75289181 100644
--- a/lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb
+++ b/lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb
@@ -9,7 +9,7 @@ module Agent
module Instrumentation
class MongodbCommandSubscriber
MONGODB = 'MongoDB'.freeze
- COLLECTION = "collection".freeze
+ COLLECTION = 'collection'.freeze
def started(event)
begin
@@ -43,7 +43,7 @@ def completed(event)
if error_key = error_key_present?(event)
# taking the last error as there can potentially be many
attributes = event.reply[error_key][-1]
- segment.notice_error(Mongo::Error.new("%s (%s)" % [attributes["errmsg"], attributes["code"]]))
+ segment.notice_error(Mongo::Error.new('%s (%s)' % [attributes['errmsg'], attributes['code']]))
# failing commands return a CommandFailed event with an error message
# in the form of "% (%s)" for the message and code
@@ -106,8 +106,8 @@ def generate_statement(event)
)
end
- UNKNOWN = "unknown".freeze
- LOCALHOST = "localhost".freeze
+ UNKNOWN = 'unknown'.freeze
+ LOCALHOST = 'localhost'.freeze
def host_from_address(address)
if unix_domain_socket?(address.host)
@@ -131,7 +131,7 @@ def port_path_or_id_from_address(address)
UNKNOWN
end
- SLASH = "/".freeze
+ SLASH = '/'.freeze
def unix_domain_socket?(host)
host.start_with?(SLASH)
diff --git a/lib/new_relic/agent/instrumentation/net_http.rb b/lib/new_relic/agent/instrumentation/net_http.rb
index 53e2f83fa8..42d179ac1b 100644
--- a/lib/new_relic/agent/instrumentation/net_http.rb
+++ b/lib/new_relic/agent/instrumentation/net_http.rb
@@ -31,7 +31,7 @@
end
conflicts_with_prepend do
- source_location_for(Net::HTTP, "request") =~ /airbrake|profiler/i
+ source_location_for(Net::HTTP, 'request') =~ /airbrake|profiler/i
end
executes do
diff --git a/lib/new_relic/agent/instrumentation/notifications_subscriber.rb b/lib/new_relic/agent/instrumentation/notifications_subscriber.rb
index 3db9809621..1bff8b2732 100644
--- a/lib/new_relic/agent/instrumentation/notifications_subscriber.rb
+++ b/lib/new_relic/agent/instrumentation/notifications_subscriber.rb
@@ -118,7 +118,7 @@ def define_exception_method
return if defined?(exception_object)
return unless defined?(::ActiveSupport::VERSION)
- if ::ActiveSupport::VERSION::STRING < "5.0.0"
+ if ::ActiveSupport::VERSION::STRING < '5.0.0'
# Earlier versions of Rails did not add the exception itself to the
# payload accessible via :exception_object, so we create a stand-in
# error object from the given class name and message.
diff --git a/lib/new_relic/agent/instrumentation/padrino/instrumentation.rb b/lib/new_relic/agent/instrumentation/padrino/instrumentation.rb
index d22ff3f79c..3f1fd096e9 100644
--- a/lib/new_relic/agent/instrumentation/padrino/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/padrino/instrumentation.rb
@@ -6,9 +6,9 @@ module NewRelic::Agent::Instrumentation
module Padrino
def invoke_route_with_tracing(*args)
begin
- env["newrelic.last_route"] = args[0].original_path
+ env['newrelic.last_route'] = args[0].original_path
rescue => e
- ::NewRelic::Agent.logger.debug("Failed determining last route in Padrino", e)
+ ::NewRelic::Agent.logger.debug('Failed determining last route in Padrino', e)
end
begin
@@ -19,7 +19,7 @@ def invoke_route_with_tracing(*args)
)
end
rescue => e
- ::NewRelic::Agent.logger.debug("Failed during invoke_route to set transaction name", e)
+ ::NewRelic::Agent.logger.debug('Failed during invoke_route to set transaction name', e)
end
yield
diff --git a/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb b/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb
index c620bc80ac..857c87f096 100644
--- a/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb
@@ -10,10 +10,10 @@
end
executes do
- NewRelic::Agent.logger.debug("Installing Passenger event hooks.")
+ NewRelic::Agent.logger.debug('Installing Passenger event hooks.')
PhusionPassenger.on_event(:stopping_worker_process) do
- NewRelic::Agent.logger.debug("Passenger stopping this process, shutdown the agent.")
+ NewRelic::Agent.logger.debug('Passenger stopping this process, shutdown the agent.')
NewRelic::Agent.instance.shutdown
end
diff --git a/lib/new_relic/agent/instrumentation/rack/instrumentation.rb b/lib/new_relic/agent/instrumentation/rack/instrumentation.rb
index 7458ac6b19..f72bbb176f 100644
--- a/lib/new_relic/agent/instrumentation/rack/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/rack/instrumentation.rb
@@ -16,7 +16,7 @@ class << builder_class
def deferred_dependency_check
return if self.class._nr_deferred_detection_ran
- NewRelic::Agent.logger.info("Doing deferred dependency-detection before Rack startup")
+ NewRelic::Agent.logger.info('Doing deferred dependency-detection before Rack startup')
DependencyDetection.detect!
self.class._nr_deferred_detection_ran = true
end
diff --git a/lib/new_relic/agent/instrumentation/rails3/action_controller.rb b/lib/new_relic/agent/instrumentation/rails3/action_controller.rb
index 8e17182f81..4c193cb0f9 100644
--- a/lib/new_relic/agent/instrumentation/rails3/action_controller.rb
+++ b/lib/new_relic/agent/instrumentation/rails3/action_controller.rb
@@ -37,7 +37,7 @@ module NewRelic
extend self
def template_metric(identifier, options = {})
if options[:file]
- "file"
+ 'file'
elsif identifier.nil?
::NewRelic::Agent::UNKNOWN_METRIC
elsif identifier.include?('/') # this is a filepath
@@ -112,7 +112,8 @@ class ActionController::Base
def render_with_newrelic(context, options)
# This is needed for rails 3.2 compatibility
@details = extract_details(options) if respond_to?(:extract_details, true)
- identifier = determine_template(options) ? determine_template(options).identifier : nil
+ # this file can't be found in SimpleCov, need to check test coverage
+ identifier = determine_template(options) ? determine_template(options).identifier : nil # rubocop:disable Style/SafeNavigation
scope_name = "View/#{NewRelic::Agent::Instrumentation::Rails3::ActionView::NewRelic.template_metric(identifier, options)}/Rendering"
trace_execution_scoped(scope_name) do
render_without_newrelic(context, options)
diff --git a/lib/new_relic/agent/instrumentation/rails_middleware.rb b/lib/new_relic/agent/instrumentation/rails_middleware.rb
index 126704f478..40fe3d280a 100644
--- a/lib/new_relic/agent/instrumentation/rails_middleware.rb
+++ b/lib/new_relic/agent/instrumentation/rails_middleware.rb
@@ -16,7 +16,7 @@
end
executes do
- NewRelic::Agent.logger.info("Installing Rails 3+ middleware instrumentation")
+ NewRelic::Agent.logger.info('Installing Rails 3+ middleware instrumentation')
module ActionDispatch
class MiddlewareStack
class Middleware
diff --git a/lib/new_relic/agent/instrumentation/rake.rb b/lib/new_relic/agent/instrumentation/rake.rb
index 579ad32661..543b52b50d 100644
--- a/lib/new_relic/agent/instrumentation/rake.rb
+++ b/lib/new_relic/agent/instrumentation/rake.rb
@@ -12,12 +12,12 @@
configure_with :rake
depends_on { defined?(Rake) && defined?(Rake::VERSION) }
- depends_on { Gem::Version.new(Rake::VERSION) >= Gem::Version.new("10.0.0") }
+ depends_on { Gem::Version.new(Rake::VERSION) >= Gem::Version.new('10.0.0') }
depends_on { NewRelic::Agent.config[:'rake.tasks'].any? }
depends_on { NewRelic::Agent::Instrumentation::Rake.safe_from_third_party_gem? }
executes do
- NewRelic::Agent.logger.info("Installing Rake instrumentation")
+ NewRelic::Agent.logger.info('Installing Rake instrumentation')
NewRelic::Agent.logger.debug("Instrumenting Rake tasks: #{NewRelic::Agent.config[:'rake.tasks']}")
end
diff --git a/lib/new_relic/agent/instrumentation/rake/instrumentation.rb b/lib/new_relic/agent/instrumentation/rake/instrumentation.rb
index d18477210e..43e5752f5c 100644
--- a/lib/new_relic/agent/instrumentation/rake/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/rake/instrumentation.rb
@@ -16,7 +16,7 @@ def invoke_with_newrelic_tracing(*args)
timeout = NewRelic::Agent.config[:'rake.connect_timeout']
NewRelic::Agent.instance.wait_on_connect(timeout)
rescue => e
- NewRelic::Agent.logger.error("Exception in wait_on_connect", e)
+ NewRelic::Agent.logger.error('Exception in wait_on_connect', e)
return yield
end
@@ -36,9 +36,9 @@ def should_install?
end
def safe_from_third_party_gem?
- return true unless NewRelic::LanguageSupport.bundled_gem?("newrelic-rake")
+ return true unless NewRelic::LanguageSupport.bundled_gem?('newrelic-rake')
- ::NewRelic::Agent.logger.info("Not installing New Relic supported Rake instrumentation because the third party newrelic-rake gem is present")
+ ::NewRelic::Agent.logger.info('Not installing New Relic supported Rake instrumentation because the third party newrelic-rake gem is present')
false
end
@@ -72,7 +72,7 @@ def execute(*args, &block)
def instrument_invoke_prerequisites_concurrently(task)
task.instance_eval do
def invoke_prerequisites_concurrently(*_)
- NewRelic::Agent::MethodTracer.trace_execution_scoped("Rake/execute/multitask") do
+ NewRelic::Agent::MethodTracer.trace_execution_scoped('Rake/execute/multitask') do
super
end
end
@@ -87,11 +87,11 @@ def before_invoke_transaction(task)
instrument_invoke_prerequisites_concurrently(task)
end
rescue => e
- NewRelic::Agent.logger.error("Error during Rake task invoke", e)
+ NewRelic::Agent.logger.error('Error during Rake task invoke', e)
end
def record_attributes(args, task)
- command_line = task.application.top_level_tasks.join(" ")
+ command_line = task.application.top_level_tasks.join(' ')
NewRelic::Agent::Transaction.merge_untrusted_agent_attributes({:command => command_line},
:'job.rake',
NewRelic::Agent::AttributeFilter::DST_NONE)
@@ -102,7 +102,7 @@ def record_attributes(args, task)
NewRelic::Agent::AttributeFilter::DST_NONE)
end
rescue => e
- NewRelic::Agent.logger.error("Error during Rake task attribute recording.", e)
+ NewRelic::Agent.logger.error('Error during Rake task attribute recording.', e)
end
# Expects literal args passed to the task and array of task names
diff --git a/lib/new_relic/agent/instrumentation/redis/constants.rb b/lib/new_relic/agent/instrumentation/redis/constants.rb
index 9ab31b3c89..d7da5af0a4 100644
--- a/lib/new_relic/agent/instrumentation/redis/constants.rb
+++ b/lib/new_relic/agent/instrumentation/redis/constants.rb
@@ -12,6 +12,6 @@ class Constants
PIPELINE_OPERATION = 'pipeline'
HAS_REDIS_CLIENT = defined?(::Redis) &&
Gem::Version.new(::Redis::VERSION) >= Gem::Version.new('5.0.0') &&
- !!defined?(::RedisClient)
+ !defined?(::RedisClient).nil?
end
end
diff --git a/lib/new_relic/agent/instrumentation/redis/instrumentation.rb b/lib/new_relic/agent/instrumentation/redis/instrumentation.rb
index 6c9a57283a..60fdf23ace 100644
--- a/lib/new_relic/agent/instrumentation/redis/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/redis/instrumentation.rb
@@ -79,7 +79,8 @@ def _nr_redis_client_config
self
# redis-client gem v0.11+ (self is a RedisClient::Middlewares)
elsif respond_to?(:client)
- client && client.config
+ # The following line needs else branch coverage
+ client && client.config # rubocop:disable Style/SafeNavigation
# redis-client gem <0.11 (self is a RedisClient::Middlewares)
elsif defined?(::RedisClient)
::RedisClient.config if ::RedisClient.respond_to?(:config)
diff --git a/lib/new_relic/agent/instrumentation/resque/helper.rb b/lib/new_relic/agent/instrumentation/resque/helper.rb
index 30438819fb..6af27e7823 100644
--- a/lib/new_relic/agent/instrumentation/resque/helper.rb
+++ b/lib/new_relic/agent/instrumentation/resque/helper.rb
@@ -10,7 +10,7 @@ module Helper
extend self
def resque_fork_per_job?
- ENV["FORK_PER_JOB"] != 'false' && NewRelic::LanguageSupport.can_fork?
+ ENV['FORK_PER_JOB'] != 'false' && NewRelic::LanguageSupport.can_fork?
end
end
end
diff --git a/lib/new_relic/agent/instrumentation/sequel.rb b/lib/new_relic/agent/instrumentation/sequel.rb
index e6396617d7..0177b90ae5 100644
--- a/lib/new_relic/agent/instrumentation/sequel.rb
+++ b/lib/new_relic/agent/instrumentation/sequel.rb
@@ -28,9 +28,9 @@ def supported_sequel_version?
if Sequel::Database.respond_to?(:extension)
Sequel::Database.extension(:new_relic_instrumentation)
else
- NewRelic::Agent.logger.info("Detected Sequel version %s." % [Sequel::VERSION])
- NewRelic::Agent.logger.info("Please see additional documentation: " +
- "https://newrelic.com/docs/ruby/sequel-instrumentation")
+ NewRelic::Agent.logger.info('Detected Sequel version %s.' % [Sequel::VERSION])
+ NewRelic::Agent.logger.info('Please see additional documentation: ' +
+ 'https://newrelic.com/docs/ruby/sequel-instrumentation')
end
Sequel.synchronize { Sequel::DATABASES.dup }.each do |db|
@@ -40,7 +40,7 @@ def supported_sequel_version?
Sequel::Model.plugin(:new_relic_instrumentation) if defined?(Sequel::Model)
else
- NewRelic::Agent.logger.info("Sequel instrumentation requires at least version 3.37.0.")
+ NewRelic::Agent.logger.info('Sequel instrumentation requires at least version 3.37.0.')
end
end
diff --git a/lib/new_relic/agent/instrumentation/sequel_helper.rb b/lib/new_relic/agent/instrumentation/sequel_helper.rb
index 3d52ef7143..8a0345749d 100644
--- a/lib/new_relic/agent/instrumentation/sequel_helper.rb
+++ b/lib/new_relic/agent/instrumentation/sequel_helper.rb
@@ -9,22 +9,22 @@ module SequelHelper
extend self
# Fallback if the product cannot be determined
- DEFAULT_PRODUCT_NAME = "Sequel".freeze
+ DEFAULT_PRODUCT_NAME = 'Sequel'.freeze
# A Sequel adapter is called an "adapter_scheme" and can be accessed from
# the database:
#
# DB.adapter_scheme
PRODUCT_NAMES = {
- :ibmdb => "IBMDB2",
- :firebird => "Firebird",
- :informix => "Informix",
- :jdbc => "JDBC",
- :mysql => "MySQL",
- :mysql2 => "MySQL",
- :oracle => "Oracle",
- :postgres => "Postgres",
- :sqlite => "SQLite"
+ :ibmdb => 'IBMDB2',
+ :firebird => 'Firebird',
+ :informix => 'Informix',
+ :jdbc => 'JDBC',
+ :mysql => 'MySQL',
+ :mysql2 => 'MySQL',
+ :oracle => 'Oracle',
+ :postgres => 'Postgres',
+ :sqlite => 'SQLite'
}.freeze
def product_name_from_adapter(adapter)
diff --git a/lib/new_relic/agent/instrumentation/sidekiq/extensions/delayed_class.rb b/lib/new_relic/agent/instrumentation/sidekiq/extensions/delayed_class.rb
index dde9c3e68a..2de46dd2e5 100644
--- a/lib/new_relic/agent/instrumentation/sidekiq/extensions/delayed_class.rb
+++ b/lib/new_relic/agent/instrumentation/sidekiq/extensions/delayed_class.rb
@@ -23,7 +23,7 @@ def newrelic_trace_args(msg, queue)
:category => 'OtherTransaction/SidekiqJob'
}
rescue => e
- NewRelic::Agent.logger.error("Failure during deserializing YAML for Sidekiq::Extensions::DelayedClass", e)
+ NewRelic::Agent.logger.error('Failure during deserializing YAML for Sidekiq::Extensions::DelayedClass', e)
NewRelic::Agent::Instrumentation::Sidekiq::Server.default_trace_args(msg)
end
end
diff --git a/lib/new_relic/agent/instrumentation/sidekiq/server.rb b/lib/new_relic/agent/instrumentation/sidekiq/server.rb
index 8c3a0b370c..b15a2cc998 100644
--- a/lib/new_relic/agent/instrumentation/sidekiq/server.rb
+++ b/lib/new_relic/agent/instrumentation/sidekiq/server.rb
@@ -21,7 +21,7 @@ def call(worker, msg, queue, *_)
NewRelic::Agent::Transaction.merge_untrusted_agent_attributes(msg['args'], :'job.sidekiq.args',
NewRelic::Agent::AttributeFilter::DST_NONE)
- ::NewRelic::Agent::DistributedTracing::accept_distributed_trace_headers(trace_headers, "Other") if ::NewRelic::Agent.config[:'distributed_tracing.enabled']
+ ::NewRelic::Agent::DistributedTracing::accept_distributed_trace_headers(trace_headers, 'Other') if ::NewRelic::Agent.config[:'distributed_tracing.enabled'] && trace_headers&.any?
yield
end
end
diff --git a/lib/new_relic/agent/instrumentation/sinatra/ignorer.rb b/lib/new_relic/agent/instrumentation/sinatra/ignorer.rb
index 2483dfa995..6e01b9a931 100644
--- a/lib/new_relic/agent/instrumentation/sinatra/ignorer.rb
+++ b/lib/new_relic/agent/instrumentation/sinatra/ignorer.rb
@@ -33,7 +33,7 @@ def set_newrelic_ignore(type, *routes)
set(:newrelic_ignores, Hash.new([])) if !respond_to?(:newrelic_ignores)
# If we call an ignore without a route, it applies to the whole app
- routes = ["*"] if routes.empty?
+ routes = ['*'] if routes.empty?
settings.newrelic_ignores[type] += routes.map do |r|
# Ugly sending to private Base#compile, but we want to mimic
diff --git a/lib/new_relic/agent/instrumentation/sinatra/instrumentation.rb b/lib/new_relic/agent/instrumentation/sinatra/instrumentation.rb
index e79efab70c..c9ff847c0c 100644
--- a/lib/new_relic/agent/instrumentation/sinatra/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/sinatra/instrumentation.rb
@@ -45,7 +45,8 @@ def install_lock
def try_to_use(app, clazz)
install_lock.synchronize do
- has_middleware = app.middleware && app.middleware.any? { |info| info && info[0] == clazz }
+ # The following line needs else branch coverage
+ has_middleware = app.middleware && app.middleware.any? { |info| info && info[0] == clazz } # rubocop:disable Style/SafeNavigation
app.use(clazz) unless has_middleware
end
end
@@ -53,9 +54,9 @@ def try_to_use(app, clazz)
# Capture last route we've seen. Will set for transaction on route_eval
def process_route_with_tracing(*args)
begin
- env["newrelic.last_route"] = args[0]
+ env['newrelic.last_route'] = args[0]
rescue => e
- ::NewRelic::Agent.logger.debug("Failed determining last route in Sinatra", e)
+ ::NewRelic::Agent.logger.debug('Failed determining last route in Sinatra', e)
end
yield
end
@@ -74,7 +75,7 @@ def route_eval_with_tracing(*args)
)
end
rescue => e
- ::NewRelic::Agent.logger.debug("Failed during route_eval to set transaction name", e)
+ ::NewRelic::Agent.logger.debug('Failed during route_eval to set transaction name', e)
end
yield
end
@@ -83,7 +84,7 @@ def get_request_params
begin
@request.params
rescue => e
- NewRelic::Agent.logger.debug("Failed to get params from Rack request.", e)
+ NewRelic::Agent.logger.debug('Failed to get params from Rack request.', e)
nil
end
end
diff --git a/lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb b/lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb
index 702e874443..b5f553c68d 100644
--- a/lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb
+++ b/lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb
@@ -47,7 +47,7 @@ def http_verb(request)
# For bare Sinatra, our override on process_route captures the last
# route into the environment for us to use later on
def route_for_sinatra(env)
- env["newrelic.last_route"]
+ env['newrelic.last_route']
end
# For Padrino, the request object has a copy of the matched route
diff --git a/lib/new_relic/agent/instrumentation/tilt/instrumentation.rb b/lib/new_relic/agent/instrumentation/tilt/instrumentation.rb
index 3a65ba04b4..8255b6ed84 100644
--- a/lib/new_relic/agent/instrumentation/tilt/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/tilt/instrumentation.rb
@@ -32,7 +32,8 @@ def render_with_tracing(*args, &block)
raise
end
ensure
- finishable.finish if finishable
+ # The following line needs else branch coverage
+ finishable.finish if finishable # rubocop:disable Style/SafeNavigation
end
end
end
diff --git a/lib/new_relic/agent/instrumentation/typhoeus/instrumentation.rb b/lib/new_relic/agent/instrumentation/typhoeus/instrumentation.rb
index cd1b5d54b9..4a7f6a648b 100644
--- a/lib/new_relic/agent/instrumentation/typhoeus/instrumentation.rb
+++ b/lib/new_relic/agent/instrumentation/typhoeus/instrumentation.rb
@@ -6,10 +6,10 @@ module NewRelic
module Agent
module Instrumentation
module Typhoeus
- HYDRA_SEGMENT_NAME = "External/Multiple/Typhoeus::Hydra/run"
- NOTICEABLE_ERROR_CLASS = "Typhoeus::Errors::TyphoeusError"
+ HYDRA_SEGMENT_NAME = 'External/Multiple/Typhoeus::Hydra/run'
+ NOTICEABLE_ERROR_CLASS = 'Typhoeus::Errors::TyphoeusError'
- EARLIEST_VERSION = Gem::Version.new("0.5.3")
+ EARLIEST_VERSION = Gem::Version.new('0.5.3')
def self.is_supported_version?
Gem::Version.new(::Typhoeus::VERSION) >= EARLIEST_VERSION
@@ -26,7 +26,7 @@ def self.response_message(response)
response.return_message
else
# 0.5.4 seems to have lost xxxx_message methods altogether.
- "timeout"
+ 'timeout'
end
end
@@ -72,7 +72,7 @@ def self.trace(request)
end
request.on_complete.unshift(callback)
rescue => e
- NewRelic::Agent.logger.error("Exception during trace setup for Typhoeus request", e)
+ NewRelic::Agent.logger.error('Exception during trace setup for Typhoeus request', e)
end
end
end
diff --git a/lib/new_relic/agent/javascript_instrumentor.rb b/lib/new_relic/agent/javascript_instrumentor.rb
index 1eeea85f78..6bce7fb51c 100644
--- a/lib/new_relic/agent/javascript_instrumentor.rb
+++ b/lib/new_relic/agent/javascript_instrumentor.rb
@@ -23,7 +23,7 @@ def log_configuration
"JS agent loader version: #{NewRelic::Agent.config[:'browser_monitoring.loader_version']}")
if !NewRelic::Agent.config[:'rum.enabled']
- NewRelic::Agent.logger.debug("Real User Monitoring is disabled for this agent. Edit your configuration to change this.")
+ NewRelic::Agent.logger.debug('Real User Monitoring is disabled for this agent. Edit your configuration to change this.')
end
end
@@ -38,19 +38,19 @@ def obfuscator
def js_enabled_and_ready?
if !enabled?
::NewRelic::Agent.logger.log_once(:debug, :js_agent_disabled,
- "JS agent instrumentation is disabled.")
+ 'JS agent instrumentation is disabled.')
false
elsif missing_config?(:js_agent_loader)
::NewRelic::Agent.logger.log_once(:debug, :missing_js_agent_loader,
- "Missing :js_agent_loader. Skipping browser instrumentation.")
+ 'Missing :js_agent_loader. Skipping browser instrumentation.')
false
elsif missing_config?(:beacon)
::NewRelic::Agent.logger.log_once(:debug, :missing_beacon,
- "Beacon configuration not received (yet?). Skipping browser instrumentation.")
+ 'Beacon configuration not received (yet?). Skipping browser instrumentation.')
false
elsif missing_config?(:browser_key)
::NewRelic::Agent.logger.log_once(:debug, :missing_browser_key,
- "Browser key is not set. Skipping browser instrumentation.")
+ 'Browser key is not set. Skipping browser instrumentation.')
false
else
true
@@ -62,19 +62,19 @@ def js_enabled_and_ready?
def insert_js?(state)
if !state.current_transaction
- ::NewRelic::Agent.logger.debug("Not in transaction. Skipping browser instrumentation.")
+ ::NewRelic::Agent.logger.debug('Not in transaction. Skipping browser instrumentation.')
false
elsif !state.is_execution_traced?
- ::NewRelic::Agent.logger.debug("Execution is not traced. Skipping browser instrumentation.")
+ ::NewRelic::Agent.logger.debug('Execution is not traced. Skipping browser instrumentation.')
false
elsif state.current_transaction.ignore_enduser?
- ::NewRelic::Agent.logger.debug("Ignore end user for this transaction is set. Skipping browser instrumentation.")
+ ::NewRelic::Agent.logger.debug('Ignore end user for this transaction is set. Skipping browser instrumentation.')
false
else
true
end
rescue => e
- ::NewRelic::Agent.logger.debug("Failure during insert_js", e)
+ ::NewRelic::Agent.logger.debug('Failure during insert_js', e)
false
end
@@ -95,7 +95,7 @@ def browser_timing_header(nonce = nil) # THREAD_LOCAL_ACCESS
bt_config + browser_timing_loader(nonce)
rescue => e
- ::NewRelic::Agent.logger.debug("Failure during RUM browser_timing_header construction", e)
+ ::NewRelic::Agent.logger.debug('Failure during RUM browser_timing_header construction', e)
''
end
@@ -122,18 +122,18 @@ def create_nonce(nonce = nil)
" nonce=\"#{nonce.to_s}\""
end
- BEACON_KEY = "beacon".freeze
- ERROR_BEACON_KEY = "errorBeacon".freeze
- LICENSE_KEY_KEY = "licenseKey".freeze
- APPLICATIONID_KEY = "applicationID".freeze
- TRANSACTION_NAME_KEY = "transactionName".freeze
- QUEUE_TIME_KEY = "queueTime".freeze
- APPLICATION_TIME_KEY = "applicationTime".freeze
- AGENT_KEY = "agent".freeze
- SSL_FOR_HTTP_KEY = "sslForHttp".freeze
- ATTS_KEY = "atts".freeze
- ATTS_USER_SUBKEY = "u".freeze
- ATTS_AGENT_SUBKEY = "a".freeze
+ BEACON_KEY = 'beacon'.freeze
+ ERROR_BEACON_KEY = 'errorBeacon'.freeze
+ LICENSE_KEY_KEY = 'licenseKey'.freeze
+ APPLICATIONID_KEY = 'applicationID'.freeze
+ TRANSACTION_NAME_KEY = 'transactionName'.freeze
+ QUEUE_TIME_KEY = 'queueTime'.freeze
+ APPLICATION_TIME_KEY = 'applicationTime'.freeze
+ AGENT_KEY = 'agent'.freeze
+ SSL_FOR_HTTP_KEY = 'sslForHttp'.freeze
+ ATTS_KEY = 'atts'.freeze
+ ATTS_USER_SUBKEY = 'u'.freeze
+ ATTS_AGENT_SUBKEY = 'a'.freeze
# NOTE: Internal prototyping may override this, so leave name stable!
def data_for_js_agent(transaction)
@@ -185,9 +185,14 @@ def add_attributes(data, txn)
def append_custom_attributes!(txn, atts)
custom_attributes = txn.attributes.custom_attributes_for(NewRelic::Agent::AttributeFilter::DST_BROWSER_MONITORING)
- unless custom_attributes.empty?
- atts[ATTS_USER_SUBKEY] = custom_attributes
+ if custom_attributes.empty?
+ NewRelic::Agent.logger.debug("#{self.class}: No custom attributes found to append.")
+ return
end
+
+ NewRelic::Agent.logger.debug("#{self.class}: Appending the following custom attribute keys for browser " \
+ "monitoring: #{custom_attributes.keys}")
+ atts[ATTS_USER_SUBKEY] = custom_attributes
end
def append_agent_attributes!(txn, atts)
diff --git a/lib/new_relic/agent/linking_metadata.rb b/lib/new_relic/agent/linking_metadata.rb
index 63a0e52aad..de37b4b888 100644
--- a/lib/new_relic/agent/linking_metadata.rb
+++ b/lib/new_relic/agent/linking_metadata.rb
@@ -11,7 +11,7 @@ module LinkingMetadata
extend self
def append_service_linking_metadata(metadata)
- raise ArgumentError, "Missing argument `metadata`" if metadata.nil?
+ raise ArgumentError, 'Missing argument `metadata`' if metadata.nil?
config = ::NewRelic::Agent.config
@@ -27,7 +27,7 @@ def append_service_linking_metadata(metadata)
end
def append_trace_linking_metadata(metadata)
- raise ArgumentError, "Missing argument `metadata`" if metadata.nil?
+ raise ArgumentError, 'Missing argument `metadata`' if metadata.nil?
if trace_id = Tracer.current_trace_id
metadata[TRACE_ID_KEY] = trace_id
diff --git a/lib/new_relic/agent/log_event_aggregator.rb b/lib/new_relic/agent/log_event_aggregator.rb
index c8273d0759..0666962d18 100644
--- a/lib/new_relic/agent/log_event_aggregator.rb
+++ b/lib/new_relic/agent/log_event_aggregator.rb
@@ -9,20 +9,20 @@ module NewRelic
module Agent
class LogEventAggregator < EventAggregator
# Per-message keys
- LEVEL_KEY = "level".freeze
- MESSAGE_KEY = "message".freeze
- TIMESTAMP_KEY = "timestamp".freeze
- PRIORITY_KEY = "priority".freeze
+ LEVEL_KEY = 'level'.freeze
+ MESSAGE_KEY = 'message'.freeze
+ TIMESTAMP_KEY = 'timestamp'.freeze
+ PRIORITY_KEY = 'priority'.freeze
# Metric keys
- LINES = "Logging/lines".freeze
- DROPPED_METRIC = "Logging/Forwarding/Dropped".freeze
- SEEN_METRIC = "Supportability/Logging/Forwarding/Seen".freeze
- SENT_METRIC = "Supportability/Logging/Forwarding/Sent".freeze
- OVERALL_SUPPORTABILITY_FORMAT = "Supportability/Logging/Ruby/Logger/%s".freeze
- METRICS_SUPPORTABILITY_FORMAT = "Supportability/Logging/Metrics/Ruby/%s".freeze
- FORWARDING_SUPPORTABILITY_FORMAT = "Supportability/Logging/Forwarding/Ruby/%s".freeze
- DECORATING_SUPPORTABILITY_FORMAT = "Supportability/Logging/LocalDecorating/Ruby/%s".freeze
+ LINES = 'Logging/lines'.freeze
+ DROPPED_METRIC = 'Logging/Forwarding/Dropped'.freeze
+ SEEN_METRIC = 'Supportability/Logging/Forwarding/Seen'.freeze
+ SENT_METRIC = 'Supportability/Logging/Forwarding/Sent'.freeze
+ OVERALL_SUPPORTABILITY_FORMAT = 'Supportability/Logging/Ruby/Logger/%s'.freeze
+ METRICS_SUPPORTABILITY_FORMAT = 'Supportability/Logging/Metrics/Ruby/%s'.freeze
+ FORWARDING_SUPPORTABILITY_FORMAT = 'Supportability/Logging/Forwarding/Ruby/%s'.freeze
+ DECORATING_SUPPORTABILITY_FORMAT = 'Supportability/Logging/LocalDecorating/Ruby/%s'.freeze
MAX_BYTES = 32768 # 32 * 1024 bytes (32 kibibytes)
named :LogEventAggregator
@@ -54,7 +54,7 @@ def capacity
def record(formatted_message, severity)
return unless enabled?
- severity = "UNKNOWN" if severity.nil? || severity.empty?
+ severity = 'UNKNOWN' if severity.nil? || severity.empty?
if NewRelic::Agent.config[METRICS_ENABLED_KEY]
@counter_lock.synchronize do
@@ -174,9 +174,9 @@ def register_for_done_configuring(events)
def record_configuration_metric(format, key)
state = NewRelic::Agent.config[key]
label = if !enabled?
- "disabled"
+ 'disabled'
else
- state ? "enabled" : "disabled"
+ state ? 'enabled' : 'disabled'
end
NewRelic::Agent.increment_metric(format % label)
end
diff --git a/lib/new_relic/agent/logging.rb b/lib/new_relic/agent/logging.rb
index 7604dfeb0b..69d58de716 100644
--- a/lib/new_relic/agent/logging.rb
+++ b/lib/new_relic/agent/logging.rb
@@ -22,16 +22,21 @@ module Logging
#
# @api public
class DecoratingFormatter < ::Logger::Formatter
- TIMESTAMP_KEY = 'timestamp'.freeze
- MESSAGE_KEY = 'message'.freeze
- LOG_LEVEL_KEY = 'log.level'.freeze
- LOG_NAME_KEY = 'logger.name'.freeze
- NEWLINE = "\n".freeze
-
- QUOTE = '"'.freeze
- COLON = ':'.freeze
- COMMA = ','.freeze
- CLOSING_BRACE = '}'.freeze
+ MESSAGE_ELEMENT = 'message'
+ LOG_LEVEL_ELEMENT = 'log_level'
+ PROG_NAME_ELEMENT = 'prog_name'
+ ELEMENTS = ['app_name', 'entity_type', 'hostname', 'entity_guid', 'trace_id', 'span_id', MESSAGE_ELEMENT,
+ LOG_LEVEL_ELEMENT, PROG_NAME_ELEMENT].freeze
+ TIMESTAMP_KEY = 'timestamp'
+ MESSAGE_KEY = 'message'
+ LOG_LEVEL_KEY = 'log.level'
+ LOG_NAME_KEY = 'logger.name'
+ NEWLINE = "\n"
+
+ QUOTE = '"'
+ COLON = ':'
+ COMMA = ','
+ CLOSING_BRACE = '}'
REPLACEMENT_CHAR = '�'
def initialize
@@ -41,41 +46,76 @@ def initialize
end
def call(severity, time, progname, msg)
- message = String.new('{')
- if app_name
- add_key_value(message, ENTITY_NAME_KEY, app_name)
- message << COMMA
+ message = +'{'
+ ELEMENTS.each do |element|
+ args = case element
+ when MESSAGE_ELEMENT then [message, msg]
+ when LOG_LEVEL_ELEMENT then [message, severity]
+ when PROG_NAME_ELEMENT then [message, progname]
+ else [message]
+ end
+
+ send("add_#{element}", *args)
end
+ message << COMMA
+ message << QUOTE << TIMESTAMP_KEY << QUOTE << COLON << (time.to_f * 1000).round.to_s
+ message << CLOSING_BRACE << NEWLINE
+ end
+
+ private
+
+ def add_app_name(message)
+ return unless app_name
+
+ add_key_value(message, ENTITY_NAME_KEY, app_name)
+ message << COMMA
+ end
+
+ def add_entity_type(message)
add_key_value(message, ENTITY_TYPE_KEY, ENTITY_TYPE)
message << COMMA
+ end
+
+ def add_hostname(message)
add_key_value(message, HOSTNAME_KEY, Hostname.get)
+ end
- if entity_guid = Agent.config[:entity_guid]
- message << COMMA
- add_key_value(message, ENTITY_GUID_KEY, entity_guid)
- end
+ def add_entity_guid(message)
+ return unless entity_guid = Agent.config[:entity_guid]
- if trace_id = Tracer.trace_id
- message << COMMA
- add_key_value(message, TRACE_ID_KEY, trace_id)
- end
- if span_id = Tracer.span_id
- message << COMMA
- add_key_value(message, SPAN_ID_KEY, span_id)
- end
+ message << COMMA
+ add_key_value(message, ENTITY_GUID_KEY, entity_guid)
+ end
+
+ def add_trace_id(message)
+ return unless trace_id = Tracer.trace_id
+ message << COMMA
+ add_key_value(message, TRACE_ID_KEY, trace_id)
+ end
+
+ def add_span_id(message)
+ return unless span_id = Tracer.span_id
+
+ message << COMMA
+ add_key_value(message, SPAN_ID_KEY, span_id)
+ end
+
+ def add_message(message, msg)
message << COMMA
message << QUOTE << MESSAGE_KEY << QUOTE << COLON << escape(msg)
message << COMMA
+ end
+
+ def add_log_level(message, severity)
add_key_value(message, LOG_LEVEL_KEY, severity)
- if progname
- message << COMMA
- add_key_value(message, LOG_NAME_KEY, progname)
- end
+ end
+
+ def add_prog_name(message, progname)
+ return unless progname
message << COMMA
- message << QUOTE << TIMESTAMP_KEY << QUOTE << COLON << (time.to_f * 1000).round.to_s
- message << CLOSING_BRACE << NEWLINE
+ add_key_value(message, LOG_NAME_KEY, progname)
end
def app_name
@@ -125,7 +165,7 @@ class DecoratingLogger < (defined?(::ActiveSupport) && defined?(::ActiveSupport:
# Positional and Keyword arguments are separated beginning with Ruby 2.7
# Signature of ::Logger constructor changes in Ruby 2.4 to have both positional and keyword args
# We pivot on Ruby 2.7 for widest supportability with least amount of hassle.
- if RUBY_VERSION < "2.7.0"
+ if RUBY_VERSION < '2.7.0'
def initialize(*args)
super(*args)
self.formatter = DecoratingFormatter.new
diff --git a/lib/new_relic/agent/messaging.rb b/lib/new_relic/agent/messaging.rb
index a701ce2523..9ead4adb9c 100644
--- a/lib/new_relic/agent/messaging.rb
+++ b/lib/new_relic/agent/messaging.rb
@@ -14,7 +14,7 @@ module Agent
module Messaging
extend self
- RABBITMQ_TRANSPORT_TYPE = "RabbitMQ"
+ RABBITMQ_TRANSPORT_TYPE = 'RabbitMQ'
ATTR_DESTINATION = AttributeFilter::DST_TRANSACTION_EVENTS |
AttributeFilter::DST_TRANSACTION_TRACER |
@@ -142,15 +142,16 @@ def wrap_message_broker_consume_transaction(library:,
txn.add_agent_attribute(:'message.queueName', queue_name, ATTR_DESTINATION) if queue_name
txn.add_agent_attribute(:'message.replyTo', reply_to, AttributeFilter::DST_NONE) if reply_to
rescue => e
- NewRelic::Agent.logger.error("Error starting Message Broker consume transaction", e)
+ NewRelic::Agent.logger.error('Error starting Message Broker consume transaction', e)
end
yield
ensure
begin
- txn.finish if txn
+ # the following line needs else branch coverage
+ txn.finish if txn # rubocop:disable Style/SafeNavigation
rescue => e
- NewRelic::Agent.logger.error("Error stopping Message Broker consume transaction", e)
+ NewRelic::Agent.logger.error('Error stopping Message Broker consume transaction', e)
end
end
@@ -190,7 +191,8 @@ def start_amqp_publish_segment(library:,
raise ArgumentError, 'missing required argument: headers' if headers.nil? && CrossAppTracing.cross_app_enabled?
- original_headers = headers.nil? ? nil : headers.dup
+ # The following line needs else branch coverage
+ original_headers = headers.nil? ? nil : headers.dup # rubocop:disable Style/SafeNavigation
segment = Tracer.start_message_broker_segment(
action: :produce,
diff --git a/lib/new_relic/agent/method_tracer.rb b/lib/new_relic/agent/method_tracer.rb
index f86c0d9c45..31115cfccd 100644
--- a/lib/new_relic/agent/method_tracer.rb
+++ b/lib/new_relic/agent/method_tracer.rb
@@ -103,7 +103,7 @@ module ClassMethods
module AddMethodTracer
ALLOWED_KEYS = [:metric, :push_scope, :code_header, :code_information, :code_footer].freeze
- DEFAULT_SETTINGS = {:push_scope => true, :metric => true, :code_header => "", :code_footer => ""}.freeze
+ DEFAULT_SETTINGS = {:push_scope => true, :metric => true, :code_header => '', :code_footer => ''}.freeze
# Checks the provided options to make sure that they make
# sense. Raises an error if the options are incorrect to
@@ -170,14 +170,14 @@ def _nr_clear_traced_methods!
def _nr_derived_class_name
return self.name if self.name && !self.name.empty?
- return "AnonymousModule" if self.to_s.start_with?("#"
name = self.to_s[/^#$/, 1]
- if name.start_with?("0x")
- "AnonymousClass"
- elsif name.start_with?("#> 31)) & 0xffffffff
app_name = NewRelic::Agent.config[:app_name].first
identifier = "#{app_name};#{txn_name}"
- sprintf("%08x", rotated ^ hash_transaction_name(identifier))
+ sprintf('%08x', rotated ^ hash_transaction_name(identifier))
end
private
@@ -44,7 +44,7 @@ def path_hash(txn_name, seed)
# :after_call will write our response headers/metrics and clean up the thread
def register_event_listeners(events)
NewRelic::Agent.logger
- .debug("Wiring up Cross Application Tracing to events after finished configuring")
+ .debug('Wiring up Cross Application Tracing to events after finished configuring')
events.subscribe(:before_call) do |env| # THREAD_LOCAL_ACCESS
if id = decoded_id(env) and should_process_request?(id)
@@ -109,7 +109,7 @@ def content_length_from_request(request)
end
def hash_transaction_name(identifier)
- Digest::MD5.digest(identifier).unpack("@12N").first & 0xffffffff
+ Digest::MD5.digest(identifier).unpack('@12N').first & 0xffffffff
end
end
end
diff --git a/lib/new_relic/agent/monitors/distributed_tracing_monitor.rb b/lib/new_relic/agent/monitors/distributed_tracing_monitor.rb
index 0f82808161..9218670549 100644
--- a/lib/new_relic/agent/monitors/distributed_tracing_monitor.rb
+++ b/lib/new_relic/agent/monitors/distributed_tracing_monitor.rb
@@ -14,7 +14,7 @@ def on_finished_configuring(events)
def on_before_call(request)
unless NewRelic::Agent.config[:'distributed_tracing.enabled']
- NewRelic::Agent.logger.warn("Not configured to accept distributed trace headers")
+ NewRelic::Agent.logger.warn('Not configured to accept distributed trace headers')
return
end
diff --git a/lib/new_relic/agent/new_relic_service.rb b/lib/new_relic/agent/new_relic_service.rb
index 225e1f2e8f..6625cb256c 100644
--- a/lib/new_relic/agent/new_relic_service.rb
+++ b/lib/new_relic/agent/new_relic_service.rb
@@ -65,7 +65,7 @@ def prep_marshaller
Agent.config.register_callback(:marshaller) do |marshaller|
if marshaller != 'json'
::NewRelic::Agent.logger.warn("Non-JSON marshaller '#{marshaller}' requested but not supported, using " \
- "JSON marshaller instead. pruby marshalling has been removed as of version 3.14.0.")
+ 'JSON marshaller instead. pruby marshalling has been removed as of version 3.14.0.')
end
@marshaller = JsonMarshaller.new
@@ -195,16 +195,16 @@ def log_event_data(data)
def error_event_data(data)
metadata, items = data
response = invoke_remote(:error_event_data, [@agent_id, *data], :item_count => items.size)
- NewRelic::Agent.record_metric("Supportability/Events/TransactionError/Sent", :count => items.size)
- NewRelic::Agent.record_metric("Supportability/Events/TransactionError/Seen", :count => metadata[:events_seen])
+ NewRelic::Agent.record_metric('Supportability/Events/TransactionError/Sent', :count => items.size)
+ NewRelic::Agent.record_metric('Supportability/Events/TransactionError/Seen', :count => metadata[:events_seen])
response
end
def span_event_data(data)
metadata, items = data
response = invoke_remote(:span_event_data, [@agent_id, *data], :item_count => items.size)
- NewRelic::Agent.record_metric("Supportability/Events/SpanEvents/Sent", :count => items.size)
- NewRelic::Agent.record_metric("Supportability/Events/SpanEvents/Seen", :count => metadata[:events_seen])
+ NewRelic::Agent.record_metric('Supportability/Events/SpanEvents/Sent', :count => items.size)
+ NewRelic::Agent.record_metric('Supportability/Events/SpanEvents/Seen', :count => metadata[:events_seen])
response
end
@@ -305,7 +305,7 @@ def setup_connection_for_ssl(conn)
conn.verify_mode = OpenSSL::SSL::VERIFY_PEER
set_cert_store(conn)
rescue StandardError, LoadError
- msg = "SSL is not available in the environment; please install SSL support."
+ msg = 'SSL is not available in the environment; please install SSL support.'
raise UnrecoverableAgentException.new(msg)
end
@@ -313,7 +313,7 @@ def set_cert_store(conn)
if NewRelic::Agent.config[:ca_bundle_path]
conn.cert_store = ssl_cert_store
else
- ::NewRelic::Agent.logger.debug("Using default security certificates")
+ ::NewRelic::Agent.logger.debug('Using default security certificates')
end
end
@@ -363,7 +363,7 @@ def create_and_start_http_connection
start_connection(conn)
conn
rescue Timeout::Error
- ::NewRelic::Agent.logger.info("Timeout while attempting to connect. You may need to install system-level CA Certificates, as the ruby agent no longer includes these.")
+ ::NewRelic::Agent.logger.info('Timeout while attempting to connect. You may need to install system-level CA Certificates, as the ruby agent no longer includes these.')
raise
end
@@ -380,7 +380,7 @@ def valid_to_marshal?(data)
@marshaller.dump(data)
true
rescue StandardError, SystemStackError => e
- NewRelic::Agent.logger.warn("Unable to marshal environment report on connect.", e)
+ NewRelic::Agent.logger.warn('Unable to marshal environment report on connect.', e)
false
end
@@ -409,7 +409,7 @@ def prep_request(opts)
end
@audit_logger.log_request_headers(opts[:uri], headers)
request['user-agent'] = user_agent
- request.content_type = "application/octet-stream"
+ request.content_type = 'application/octet-stream'
request.body = opts[:data]
request
end
@@ -521,7 +521,7 @@ def generate_remote_method_uri(method)
# ruled out; see the initializer
}
- uri = String.new('/agent_listener/invoke_raw_method?')
+ uri = +'/agent_listener/invoke_raw_method?'
uri << params.map do |k, v|
next unless v
@@ -551,7 +551,7 @@ def invoke_remote(method, payload = [], options = {})
end
def handle_serialization_error(method, e)
- NewRelic::Agent.increment_metric("Supportability/serialization_failure")
+ NewRelic::Agent.increment_metric('Supportability/serialization_failure')
NewRelic::Agent.increment_metric("Supportability/serialization_failure/#{method}")
msg = "Failed to serialize #{method} data using #{@marshaller.class}: #{e.inspect}"
error = SerializationError.new(msg)
@@ -566,7 +566,7 @@ def record_timing_supportability_metrics(method, start_ts, serialize_finish_ts,
NewRelic::Agent.record_metric("Supportability/Agent/Collector/#{method}/Duration", request_duration)
end
if serialize_time
- NewRelic::Agent.record_metric("Supportability/invoke_remote_serialize", serialize_time)
+ NewRelic::Agent.record_metric('Supportability/invoke_remote_serialize', serialize_time)
NewRelic::Agent.record_metric("Supportability/invoke_remote_serialize/#{method}", serialize_time)
end
end
@@ -581,7 +581,7 @@ def record_timing_supportability_metrics(method, start_ts, serialize_finish_ts,
# of items as arguments.
def record_size_supportability_metrics(method, size_bytes, item_count)
metrics = [
- "Supportability/Ruby/Collector/Output/Bytes",
+ 'Supportability/Ruby/Collector/Output/Bytes',
"Supportability/Ruby/Collector/#{method}/Output/Bytes"
]
# we may not have an item count, in which case, just record 0 for the exclusive time
diff --git a/lib/new_relic/agent/new_relic_service/encoders.rb b/lib/new_relic/agent/new_relic_service/encoders.rb
index 3868f699bd..b588b7ced5 100644
--- a/lib/new_relic/agent/new_relic_service/encoders.rb
+++ b/lib/new_relic/agent/new_relic_service/encoders.rb
@@ -25,7 +25,7 @@ def self.encode(data, opts = nil)
end
module Gzip
- BINARY = "BINARY".freeze
+ BINARY = 'BINARY'.freeze
def self.encode(data, opts = nil)
output = StringIO.new
diff --git a/lib/new_relic/agent/new_relic_service/json_marshaller.rb b/lib/new_relic/agent/new_relic_service/json_marshaller.rb
index 9693dd2a66..26a08909ef 100644
--- a/lib/new_relic/agent/new_relic_service/json_marshaller.rb
+++ b/lib/new_relic/agent/new_relic_service/json_marshaller.rb
@@ -14,7 +14,7 @@ def initialize
warn_for_yajl
end
- OK_YAJL_VERSION = Gem::Version.new("1.2.1")
+ OK_YAJL_VERSION = Gem::Version.new('1.2.1')
def warn_for_yajl
if defined?(::Yajl)
@@ -24,7 +24,7 @@ def warn_for_yajl
end
end
rescue => err
- ::NewRelic::Agent.logger.warn("Failed trying to watch for problematic yajl-ruby version.", err)
+ ::NewRelic::Agent.logger.warn('Failed trying to watch for problematic yajl-ruby version.', err)
end
def dump(ruby, opts = {})
diff --git a/lib/new_relic/agent/obfuscator.rb b/lib/new_relic/agent/obfuscator.rb
index 1961c5352f..12bc9806bb 100644
--- a/lib/new_relic/agent/obfuscator.rb
+++ b/lib/new_relic/agent/obfuscator.rb
@@ -33,7 +33,7 @@ def deobfuscate(text)
def encode(text)
return text unless key_bytes
- encoded = String.new('')
+ encoded = +''
encoded.force_encoding('binary') if encoded.respond_to?(:force_encoding)
index = 0
text.each_byte do |byte|
diff --git a/lib/new_relic/agent/parameter_filtering.rb b/lib/new_relic/agent/parameter_filtering.rb
index 0eeed8890c..60f7645ad2 100644
--- a/lib/new_relic/agent/parameter_filtering.rb
+++ b/lib/new_relic/agent/parameter_filtering.rb
@@ -7,7 +7,7 @@ module Agent
module ParameterFiltering
extend self
- ACTION_DISPATCH_PARAMETER_FILTER ||= "action_dispatch.parameter_filter".freeze
+ ACTION_DISPATCH_PARAMETER_FILTER ||= 'action_dispatch.parameter_filter'.freeze
if defined?(Rails) && Gem::Version.new(::Rails::VERSION::STRING) >= Gem::Version.new('5.0.0')
Rails.application.config.to_prepare do
@@ -41,12 +41,12 @@ def filter_using_rails(params, filters)
end
def filter_rack_file_data(env, params)
- content_type = env["CONTENT_TYPE"]
- multipart = content_type && content_type.start_with?("multipart")
+ content_type = env['CONTENT_TYPE']
+ multipart = content_type&.start_with?('multipart')
params.inject({}) do |memo, (k, v)|
if multipart && v.is_a?(Hash) && v[:tempfile]
- memo[k] = "[FILE]"
+ memo[k] = '[FILE]'
else
memo[k] = v
end
@@ -56,8 +56,8 @@ def filter_rack_file_data(env, params)
def filter_rails_request_parameters(params)
result = params.dup
- result.delete("controller")
- result.delete("action")
+ result.delete('controller')
+ result.delete('action')
result
end
diff --git a/lib/new_relic/agent/pipe_channel_manager.rb b/lib/new_relic/agent/pipe_channel_manager.rb
index 592c8bc859..4ae8a85234 100644
--- a/lib/new_relic/agent/pipe_channel_manager.rb
+++ b/lib/new_relic/agent/pipe_channel_manager.rb
@@ -55,7 +55,7 @@ def listener
# 4 GB - much larger than we'd ever need or want for this application.
#
class Pipe
- READY_MARKER = "READY"
+ READY_MARKER = 'READY'
NUM_LENGTH_BYTES = 4
attr_accessor :in, :out
@@ -76,11 +76,11 @@ def close
end
def serialize_message_length(data)
- [data.bytesize].pack("L>")
+ [data.bytesize].pack('L>')
end
def deserialize_message_length(data)
- data.unpack("L>").first
+ data.unpack('L>').first
end
def write(data)
@@ -103,7 +103,7 @@ def read
nil
end
else
- NewRelic::Agent.logger.error("Failed to read bytes for length from pipe.")
+ NewRelic::Agent.logger.error('Failed to read bytes for length from pipe.')
nil
end
end
@@ -218,7 +218,8 @@ def stop
def close_all_pipes
@pipes_lock.synchronize do
@pipes.each do |id, pipe|
- pipe.close if pipe
+ # Needs else branch coverage
+ pipe.close if pipe # rubocop:disable Style/SafeNavigation
end
@pipes = {}
end
@@ -255,7 +256,7 @@ def merge_data_from_pipe(pipe_handle)
def unmarshal(data)
Marshal.load(data)
rescue StandardError => e
- ::NewRelic::Agent.logger.error("Failure unmarshalling message from Resque child process", e)
+ ::NewRelic::Agent.logger.error('Failure unmarshalling message from Resque child process', e)
::NewRelic::Agent.logger.debug(Base64.encode64(data))
nil
end
diff --git a/lib/new_relic/agent/pipe_service.rb b/lib/new_relic/agent/pipe_service.rb
index 53deed6e11..57797bfe94 100644
--- a/lib/new_relic/agent/pipe_service.rb
+++ b/lib/new_relic/agent/pipe_service.rb
@@ -15,7 +15,7 @@ def initialize(channel_id)
if @pipe && @pipe.parent_pid != $$
@pipe.after_fork_in_child
else
- NewRelic::Agent.logger.error("No communication channel to parent process, please see https://newrelic.com/docs/ruby/resque-instrumentation for more information.")
+ NewRelic::Agent.logger.error('No communication channel to parent process, please see https://newrelic.com/docs/ruby/resque-instrumentation for more information.')
end
end
@@ -65,7 +65,8 @@ def log_event_data(logs)
end
def shutdown
- @pipe.close if @pipe
+ # no else branch coverage
+ @pipe.close if @pipe # rubocop:disable Style/SafeNavigation
end
# Invokes the block it is passed. This is used to implement HTTP
@@ -82,7 +83,8 @@ def marshal_payload(data)
end
def write_to_pipe(endpoint, data)
- @pipe.write(marshal_payload([endpoint, data])) if @pipe
+ # the following line needs else branch coverage
+ @pipe.write(marshal_payload([endpoint, data])) if @pipe # rubocop:disable Style/SafeNavigation
end
end
end
diff --git a/lib/new_relic/agent/priority_sampled_buffer.rb b/lib/new_relic/agent/priority_sampled_buffer.rb
index 5dd8adce57..ccf73ece1e 100644
--- a/lib/new_relic/agent/priority_sampled_buffer.rb
+++ b/lib/new_relic/agent/priority_sampled_buffer.rb
@@ -8,7 +8,7 @@
module NewRelic
module Agent
class PrioritySampledBuffer < EventBuffer
- PRIORITY_KEY = "priority".freeze
+ PRIORITY_KEY = 'priority'.freeze
attr_reader :seen_lifetime, :captured_lifetime
diff --git a/lib/new_relic/agent/sampler.rb b/lib/new_relic/agent/sampler.rb
index 3c7588d287..919bde7746 100644
--- a/lib/new_relic/agent/sampler.rb
+++ b/lib/new_relic/agent/sampler.rb
@@ -56,7 +56,7 @@ def initialize(id = nil)
end
def poll
- raise "Implement in the subclass"
+ raise 'Implement in the subclass'
end
end
end
diff --git a/lib/new_relic/agent/sampler_collection.rb b/lib/new_relic/agent/sampler_collection.rb
index 8298fa0edd..a0cd2d02f8 100644
--- a/lib/new_relic/agent/sampler_collection.rb
+++ b/lib/new_relic/agent/sampler_collection.rb
@@ -64,7 +64,7 @@ def add_sampler(sampler_class)
rescue NewRelic::Agent::Sampler::Unsupported => e
::NewRelic::Agent.logger.info("#{sampler_class.name} not available: #{e}")
rescue => e
- ::NewRelic::Agent.logger.error("Error registering sampler:", e)
+ ::NewRelic::Agent.logger.error('Error registering sampler:', e)
end
end
end
diff --git a/lib/new_relic/agent/samplers/cpu_sampler.rb b/lib/new_relic/agent/samplers/cpu_sampler.rb
index 673e0e3164..3dcb65bf2d 100644
--- a/lib/new_relic/agent/samplers/cpu_sampler.rb
+++ b/lib/new_relic/agent/samplers/cpu_sampler.rb
@@ -16,26 +16,26 @@ def initialize
@last_time = nil
@processor_count = NewRelic::Agent::SystemInfo.num_logical_processors
if @processor_count.nil?
- NewRelic::Agent.logger.warn("Failed to determine processor count, assuming 1")
+ NewRelic::Agent.logger.warn('Failed to determine processor count, assuming 1')
@processor_count = 1
end
poll
end
def record_user_util(value)
- NewRelic::Agent.record_metric("CPU/User/Utilization", value)
+ NewRelic::Agent.record_metric('CPU/User/Utilization', value)
end
def record_system_util(value)
- NewRelic::Agent.record_metric("CPU/System/Utilization", value)
+ NewRelic::Agent.record_metric('CPU/System/Utilization', value)
end
def record_usertime(value)
- NewRelic::Agent.record_metric("CPU/User Time", value)
+ NewRelic::Agent.record_metric('CPU/User Time', value)
end
def record_systemtime(value)
- NewRelic::Agent.record_metric("CPU/System Time", value)
+ NewRelic::Agent.record_metric('CPU/System Time', value)
end
def self.supported_on_this_platform?
diff --git a/lib/new_relic/agent/samplers/delayed_job_sampler.rb b/lib/new_relic/agent/samplers/delayed_job_sampler.rb
index 5e680e6f32..672f527fda 100644
--- a/lib/new_relic/agent/samplers/delayed_job_sampler.rb
+++ b/lib/new_relic/agent/samplers/delayed_job_sampler.rb
@@ -21,21 +21,21 @@ class DelayedJobSampler < NewRelic::Agent::Sampler
# DelayedJob supports multiple backends, only some of which we can
# handle. Check whether we think we've got what we need here.
def self.supported_backend?
- ::Delayed::Worker.backend.to_s == "Delayed::Backend::ActiveRecord::Job"
+ ::Delayed::Worker.backend.to_s == 'Delayed::Backend::ActiveRecord::Job'
end
def initialize
- raise Unsupported, "DJ queue sampler disabled" if Agent.config[:'instrumentation.delayed_job'] == 'disabled'
+ raise Unsupported, 'DJ queue sampler disabled' if Agent.config[:'instrumentation.delayed_job'] == 'disabled'
raise Unsupported, "DJ queue sampling unsupported with backend '#{::Delayed::Worker.backend}'" unless self.class.supported_backend?
- raise Unsupported, "No DJ worker present. Skipping DJ queue sampler" unless NewRelic::DelayedJobInjection.worker_name
+ raise Unsupported, 'No DJ worker present. Skipping DJ queue sampler' unless NewRelic::DelayedJobInjection.worker_name
end
def record_failed_jobs(value)
- NewRelic::Agent.record_metric("Workers/DelayedJob/failed_jobs", value)
+ NewRelic::Agent.record_metric('Workers/DelayedJob/failed_jobs', value)
end
def record_locked_jobs(value)
- NewRelic::Agent.record_metric("Workers/DelayedJob/locked_jobs", value)
+ NewRelic::Agent.record_metric('Workers/DelayedJob/locked_jobs', value)
end
FAILED_QUERY = 'failed_at is not NULL'.freeze
@@ -74,10 +74,10 @@ def poll
def record_queue_length_metrics
counts = []
- counts << record_counts_by("queue", "name") if ::Delayed::Job.instance_methods.include?(:queue)
- counts << record_counts_by("priority")
+ counts << record_counts_by('queue', 'name') if ::Delayed::Job.instance_methods.include?(:queue)
+ counts << record_counts_by('priority')
- all_metric = "Workers/DelayedJob/queue_length/all"
+ all_metric = 'Workers/DelayedJob/queue_length/all'
NewRelic::Agent.record_metric(all_metric, counts.max)
end
@@ -87,7 +87,7 @@ def record_counts_by(column_name, metric_node = column_name)
all_count = 0
queue_counts(column_name).each do |column_val, count|
all_count += count
- column_val = "default" if column_val.nil? || column_val == NewRelic::EMPTY_STR
+ column_val = 'default' if column_val.nil? || column_val == NewRelic::EMPTY_STR
metric = "Workers/DelayedJob/queue_length/#{metric_node}/#{column_val}"
NewRelic::Agent.record_metric(metric, count)
end
diff --git a/lib/new_relic/agent/samplers/memory_sampler.rb b/lib/new_relic/agent/samplers/memory_sampler.rb
index 903e979934..b141008dc1 100644
--- a/lib/new_relic/agent/samplers/memory_sampler.rb
+++ b/lib/new_relic/agent/samplers/memory_sampler.rb
@@ -23,18 +23,18 @@ def initialize
@sampler = ProcStatus.new
if !@sampler.can_run?
::NewRelic::Agent.logger.debug("Error attempting to use /proc/#{$$}/status file for reading memory. Using ps command instead.")
- @sampler = ShellPS.new("ps -o rsz")
+ @sampler = ShellPS.new('ps -o rsz')
else
::NewRelic::Agent.logger.debug("Using /proc/#{$$}/status for reading process memory.")
end
elsif platform.include?('darwin9') # 10.5
- @sampler = ShellPS.new("ps -o rsz")
- elsif platform =~ /darwin(1|2)\d+/ # >= 10.6
- @sampler = ShellPS.new("ps -o rss")
+ @sampler = ShellPS.new('ps -o rsz')
+ elsif /darwin(1|2)\d+/.match?(platform) # >= 10.6
+ @sampler = ShellPS.new('ps -o rss')
elsif platform.include?('freebsd')
- @sampler = ShellPS.new("ps -o rss")
+ @sampler = ShellPS.new('ps -o rss')
elsif platform.include?('solaris')
- @sampler = ShellPS.new("/usr/bin/ps -o rss -p")
+ @sampler = ShellPS.new('/usr/bin/ps -o rss -p')
end
raise Unsupported, "Unsupported platform for getting memory: #{platform}" if @sampler.nil?
@@ -64,7 +64,7 @@ def platform
def poll
sample = @sampler.get_sample
if sample
- NewRelic::Agent.record_metric("Memory/Physical", sample)
+ NewRelic::Agent.record_metric('Memory/Physical', sample)
end
end
@@ -106,7 +106,7 @@ def get_memory
end
def to_s
- "JRuby Java heap sampler"
+ 'JRuby Java heap sampler'
end
end
@@ -140,7 +140,7 @@ def to_s
class ProcStatus < Base
# Returns the amount of resident memory this process is using in MB
def get_memory
- proc_status = File.open(proc_status_file, "r") { |f| f.read_nonblock(4096).strip }
+ proc_status = File.open(proc_status_file, 'r') { |f| f.read_nonblock(4096).strip }
if proc_status =~ /RSS:\s*(\d+) kB/i
return $1.to_f / 1024.0
end
diff --git a/lib/new_relic/agent/samplers/object_sampler.rb b/lib/new_relic/agent/samplers/object_sampler.rb
index cd82ac1887..e5ef0eeeea 100644
--- a/lib/new_relic/agent/samplers/object_sampler.rb
+++ b/lib/new_relic/agent/samplers/object_sampler.rb
@@ -16,7 +16,7 @@ def self.supported_on_this_platform?
def poll
live_objects = ObjectSpace.live_objects
- NewRelic::Agent.record_metric("GC/objects", live_objects)
+ NewRelic::Agent.record_metric('GC/objects', live_objects)
end
end
end
diff --git a/lib/new_relic/agent/span_event_aggregator.rb b/lib/new_relic/agent/span_event_aggregator.rb
index a90542c0a6..885ff6ca1c 100644
--- a/lib/new_relic/agent/span_event_aggregator.rb
+++ b/lib/new_relic/agent/span_event_aggregator.rb
@@ -18,7 +18,7 @@ class SpanEventAggregator < EventAggregator
def record(priority: nil, event: nil, &blk)
unless event || priority && blk
- raise ArgumentError, "Expected priority and block, or event"
+ raise ArgumentError, 'Expected priority and block, or event'
end
return unless enabled?
@@ -29,9 +29,9 @@ def record(priority: nil, event: nil, &blk)
end
end
- SUPPORTABILITY_TOTAL_SEEN = "Supportability/SpanEvent/TotalEventsSeen".freeze
- SUPPORTABILITY_TOTAL_SENT = "Supportability/SpanEvent/TotalEventsSent".freeze
- SUPPORTABILITY_DISCARDED = "Supportability/SpanEvent/Discarded".freeze
+ SUPPORTABILITY_TOTAL_SEEN = 'Supportability/SpanEvent/TotalEventsSeen'.freeze
+ SUPPORTABILITY_TOTAL_SENT = 'Supportability/SpanEvent/TotalEventsSent'.freeze
+ SUPPORTABILITY_DISCARDED = 'Supportability/SpanEvent/Discarded'.freeze
def after_harvest(metadata)
seen = metadata[:seen]
diff --git a/lib/new_relic/agent/span_event_primitive.rb b/lib/new_relic/agent/span_event_primitive.rb
index 2262a011ab..2e33cc4931 100644
--- a/lib/new_relic/agent/span_event_primitive.rb
+++ b/lib/new_relic/agent/span_event_primitive.rb
@@ -37,8 +37,8 @@ module SpanEventPrimitive
PEER_HOSTNAME_KEY = 'peer.hostname'
SPAN_KIND_KEY = 'span.kind'
ENTRY_POINT_KEY = 'nr.entryPoint'
- TRUSTED_PARENT_KEY = "trustedParentId"
- TRACING_VENDORS_KEY = "tracingVendors"
+ TRUSTED_PARENT_KEY = 'trustedParentId'
+ TRACING_VENDORS_KEY = 'tracingVendors'
TRANSACTION_NAME_KEY = 'transaction.name'
# Strings for static values of the event structure
diff --git a/lib/new_relic/agent/sql_sampler.rb b/lib/new_relic/agent/sql_sampler.rb
index f9dc67f757..0ff0f08a08 100644
--- a/lib/new_relic/agent/sql_sampler.rb
+++ b/lib/new_relic/agent/sql_sampler.rb
@@ -154,12 +154,12 @@ def notice_sql(sql, metric_name, config, duration, state = nil, explainer = nil,
end
end
- PRIORITY = "priority".freeze
+ PRIORITY = 'priority'.freeze
def distributed_trace_attributes(state)
transaction = state.current_transaction
params = nil
- if transaction && transaction.distributed_tracer.distributed_trace_payload
+ if transaction&.distributed_tracer&.distributed_trace_payload
params = {}
payload = transaction.distributed_tracer.distributed_trace_payload
DistributedTraceAttributes.copy_from_transaction(transaction, payload, params)
diff --git a/lib/new_relic/agent/stats.rb b/lib/new_relic/agent/stats.rb
index 14536889c6..c54ffa8cd2 100644
--- a/lib/new_relic/agent/stats.rb
+++ b/lib/new_relic/agent/stats.rb
@@ -118,7 +118,7 @@ def increment_count(value = 1)
def inspect_full
variables = instance_variables.map do |ivar|
"#{ivar.to_s}=#{instance_variable_get(ivar).inspect}"
- end.join(" ")
+ end.join(' ')
"#"
end
diff --git a/lib/new_relic/agent/synthetics_event_aggregator.rb b/lib/new_relic/agent/synthetics_event_aggregator.rb
index 9467433137..10ed757acf 100644
--- a/lib/new_relic/agent/synthetics_event_aggregator.rb
+++ b/lib/new_relic/agent/synthetics_event_aggregator.rb
@@ -37,7 +37,7 @@ def record_dropped_synthetics(metadata)
NewRelic::Agent.logger.debug("Synthetics transaction event limit (#{metadata[:capacity]}) reached. Further synthetics events this harvest period dropped.")
engine = NewRelic::Agent.instance.stats_engine
- engine.tl_record_supportability_metric_count("SyntheticsEventAggregator/synthetics_events_dropped", num_dropped)
+ engine.tl_record_supportability_metric_count('SyntheticsEventAggregator/synthetics_events_dropped', num_dropped)
end
end
end
diff --git a/lib/new_relic/agent/system_info.rb b/lib/new_relic/agent/system_info.rb
index 5080ac574a..5d72674445 100644
--- a/lib/new_relic/agent/system_info.rb
+++ b/lib/new_relic/agent/system_info.rb
@@ -128,7 +128,7 @@ def self.parse_cpuinfo(cpuinfo)
num_physical_packages = cores.keys.map(&:first).uniq.size
num_physical_cores = cores.size
- num_logical_processors = cores.values.reduce(0, :+)
+ num_logical_processors = cores.values.sum
if num_physical_cores == 0
num_logical_processors = total_processors
@@ -202,7 +202,7 @@ def self.parse_docker_container_id(cgroup_info)
return
when /docker/
::NewRelic::Agent.logger.debug("Cgroup indicates docker but container_id unrecognized: '#{cpu_cgroup}'")
- ::NewRelic::Agent.increment_metric("Supportability/utilization/docker/error")
+ ::NewRelic::Agent.increment_metric('Supportability/utilization/docker/error')
return
else
::NewRelic::Agent.logger.debug("Ignoring unrecognized cgroup ID format: '#{cpu_cgroup}'")
@@ -211,7 +211,7 @@ def self.parse_docker_container_id(cgroup_info)
if container_id && container_id.size != 64
::NewRelic::Agent.logger.debug("Found docker container_id with invalid length: #{container_id}")
- ::NewRelic::Agent.increment_metric("Supportability/utilization/docker/error")
+ ::NewRelic::Agent.increment_metric('Supportability/utilization/docker/error')
nil
else
container_id
@@ -242,7 +242,7 @@ def self.parse_cgroup_ids(cgroup_info)
def self.proc_try_read(path)
return nil unless File.exist?(path)
- content = String.new('')
+ content = +''
File.open(path) do |f|
loop do
begin
@@ -289,8 +289,8 @@ def self.boot_id
if bid.ascii_only?
if bid.empty?
- ::NewRelic::Agent.logger.debug("boot_id not found in /proc/sys/kernel/random/boot_id")
- ::NewRelic::Agent.increment_metric("Supportability/utilization/boot_id/error")
+ ::NewRelic::Agent.logger.debug('boot_id not found in /proc/sys/kernel/random/boot_id')
+ ::NewRelic::Agent.increment_metric('Supportability/utilization/boot_id/error')
nil
elsif bid.bytesize == 36
@@ -298,19 +298,19 @@ def self.boot_id
else
::NewRelic::Agent.logger.debug("Found boot_id with invalid length: #{bid}")
- ::NewRelic::Agent.increment_metric("Supportability/utilization/boot_id/error")
+ ::NewRelic::Agent.increment_metric('Supportability/utilization/boot_id/error')
bid[0, 128]
end
else
::NewRelic::Agent.logger.debug("Found boot_id with non-ASCII characters: #{bid}")
- ::NewRelic::Agent.increment_metric("Supportability/utilization/boot_id/error")
+ ::NewRelic::Agent.increment_metric('Supportability/utilization/boot_id/error')
nil
end
else
- ::NewRelic::Agent.logger.debug("boot_id not found in /proc/sys/kernel/random/boot_id")
- ::NewRelic::Agent.increment_metric("Supportability/utilization/boot_id/error")
+ ::NewRelic::Agent.logger.debug('boot_id not found in /proc/sys/kernel/random/boot_id')
+ ::NewRelic::Agent.increment_metric('Supportability/utilization/boot_id/error')
nil
end
diff --git a/lib/new_relic/agent/threading/agent_thread.rb b/lib/new_relic/agent/threading/agent_thread.rb
index 3b364475c7..21e16d53c0 100644
--- a/lib/new_relic/agent/threading/agent_thread.rb
+++ b/lib/new_relic/agent/threading/agent_thread.rb
@@ -45,7 +45,7 @@ def self.bucket_thread(thread, profile_agent_code) # THREAD_LOCAL_ACCESS
if txn && !txn.recording_web_transaction?
:background
- elsif txn && txn.recording_web_transaction?
+ elsif txn&.recording_web_transaction?
:request
else
:other
diff --git a/lib/new_relic/agent/threading/backtrace_node.rb b/lib/new_relic/agent/threading/backtrace_node.rb
index 8c5babfbb5..d074f718ca 100644
--- a/lib/new_relic/agent/threading/backtrace_node.rb
+++ b/lib/new_relic/agent/threading/backtrace_node.rb
@@ -70,7 +70,7 @@ def aggregate(backtrace)
end
def dump_string
- result = String.new("#")
+ result = +"#"
child_results = @children.map { |c| c.dump_string(2) }.join("\n")
result << "\n" unless child_results.empty?
result << child_results
@@ -116,8 +116,8 @@ def complete_array_conversion
def dump_string(indent = 0)
@file, @method, @line_no = parse_backtrace_frame(@raw_line)
indentation = ' ' * indent
- result = String.new("#{indentation}#")
+ result = +"#{indentation}#"
child_results = @children.map { |c| c.dump_string(indent + 2) }.join("\n")
result << "\n" unless child_results.empty?
result << child_results
diff --git a/lib/new_relic/agent/threading/backtrace_service.rb b/lib/new_relic/agent/threading/backtrace_service.rb
index e0a268658c..3e2bdaa0f9 100644
--- a/lib/new_relic/agent/threading/backtrace_service.rb
+++ b/lib/new_relic/agent/threading/backtrace_service.rb
@@ -6,7 +6,7 @@ module NewRelic
module Agent
module Threading
class BacktraceService
- ALL_TRANSACTIONS = "**ALL**".freeze
+ ALL_TRANSACTIONS = '**ALL**'.freeze
def self.is_supported?
!is_resque?
@@ -41,9 +41,7 @@ def initialize(event_listener = nil)
@overhead_percent_threshold = new_value
end
- if event_listener
- event_listener.subscribe(:transaction_finished, &method(:on_transaction_finished))
- end
+ event_listener&.subscribe(:transaction_finished, &method(:on_transaction_finished))
end
# Public interface
@@ -221,9 +219,7 @@ def buffer_backtrace_for_thread(thread, timestamp, backtrace, bucket)
# This method is expected to be called with @lock held.
def aggregate_global_backtrace(backtrace, bucket, thread)
- if @profiles[ALL_TRANSACTIONS]
- @profiles[ALL_TRANSACTIONS].aggregate(backtrace, bucket, thread)
- end
+ @profiles[ALL_TRANSACTIONS]&.aggregate(backtrace, bucket, thread)
end
# This method is expected to be called with @lock held.
diff --git a/lib/new_relic/agent/threading/thread_profile.rb b/lib/new_relic/agent/threading/thread_profile.rb
index 41765bb271..19a78a0fce 100644
--- a/lib/new_relic/agent/threading/thread_profile.rb
+++ b/lib/new_relic/agent/threading/thread_profile.rb
@@ -72,7 +72,7 @@ def convert_N_trace_nodes_to_arrays(count_to_keep) # THREAD_LOCAL_ACCESS
all_nodes = @traces.values.map { |n| n.flattened }.flatten
NewRelic::Agent.instance.stats_engine
- .tl_record_supportability_metric_count("ThreadProfiler/NodeCount", all_nodes.size)
+ .tl_record_supportability_metric_count('ThreadProfiler/NodeCount', all_nodes.size)
all_nodes.sort! do |a, b|
# we primarily prefer higher runnable_count
@@ -103,10 +103,10 @@ def generate_traces
convert_N_trace_nodes_to_arrays(THREAD_PROFILER_NODES)
{
- "OTHER" => @traces[:other].as_array,
- "REQUEST" => @traces[:request].as_array,
- "AGENT" => @traces[:agent].as_array,
- "BACKGROUND" => @traces[:background].as_array
+ 'OTHER' => @traces[:other].as_array,
+ 'REQUEST' => @traces[:request].as_array,
+ 'AGENT' => @traces[:agent].as_array,
+ 'BACKGROUND' => @traces[:background].as_array
}
end
diff --git a/lib/new_relic/agent/timestamp_sampled_buffer.rb b/lib/new_relic/agent/timestamp_sampled_buffer.rb
index 507f55e737..9959542aad 100644
--- a/lib/new_relic/agent/timestamp_sampled_buffer.rb
+++ b/lib/new_relic/agent/timestamp_sampled_buffer.rb
@@ -7,7 +7,7 @@
module NewRelic
module Agent
class TimestampSampledBuffer < PrioritySampledBuffer
- TIMESTAMP_KEY = "timestamp".freeze
+ TIMESTAMP_KEY = 'timestamp'.freeze
private
diff --git a/lib/new_relic/agent/tracer.rb b/lib/new_relic/agent/tracer.rb
index 74e9f91b81..4e1b0383e4 100644
--- a/lib/new_relic/agent/tracer.rb
+++ b/lib/new_relic/agent/tracer.rb
@@ -107,7 +107,7 @@ def in_transaction(name: nil,
current_transaction.notice_error(exception)
raise
ensure
- finishable.finish if finishable
+ finishable&.finish
end
end
@@ -246,8 +246,8 @@ def start_segment(name:,
log_error('start_segment', exception)
end
- UNKNOWN = "Unknown".freeze
- OTHER = "other".freeze
+ UNKNOWN = 'Unknown'.freeze
+ OTHER = 'other'.freeze
# Creates and starts a datastore segment used to time
# datastore operations.
@@ -355,7 +355,8 @@ def capture_segment_error(segment)
yield
rescue => exception
- if segment && segment.is_a?(Transaction::AbstractSegment)
+ # needs else branch coverage
+ if segment && segment.is_a?(Transaction::AbstractSegment) # rubocop:disable Style/SafeNavigation
segment.notice_error(exception)
end
raise
@@ -425,6 +426,7 @@ def thread_block_with_current_transaction(*args, segment_name:, parent: nil, &bl
begin
if current_txn
NewRelic::Agent::Tracer.state.current_transaction = current_txn
+ current_txn.async = true
segment_name += "/Thread#{::Thread.current.object_id}/Fiber#{::Fiber.current.object_id}" if NewRelic::Agent.config[:'thread_ids_enabled']
segment = NewRelic::Agent::Tracer.start_segment(name: segment_name, parent: parent)
end
@@ -487,7 +489,8 @@ def push_traced(should_trace)
end
def pop_traced
- @untraced.pop if @untraced
+ # needs else branch coverage
+ @untraced.pop if @untraced # rubocop:disable Style/SafeNavigation
end
def is_execution_traced?
@@ -507,7 +510,5 @@ def is_sql_recorded?
attr_accessor :sql_sampler_transaction_data
end
end
-
- TransactionState = Tracer
end
end
diff --git a/lib/new_relic/agent/transaction.rb b/lib/new_relic/agent/transaction.rb
index 01ddf3f9ba..ec515c1a32 100644
--- a/lib/new_relic/agent/transaction.rb
+++ b/lib/new_relic/agent/transaction.rb
@@ -23,10 +23,10 @@ class Transaction
include Tracing
# for nested transactions
- NESTED_TRANSACTION_PREFIX = "Nested/"
- CONTROLLER_PREFIX = "Controller/"
- MIDDLEWARE_PREFIX = "Middleware/Rack/"
- OTHER_TRANSACTION_PREFIX = "OtherTransaction/"
+ NESTED_TRANSACTION_PREFIX = 'Nested/'
+ CONTROLLER_PREFIX = 'Controller/'
+ MIDDLEWARE_PREFIX = 'Middleware/Rack/'
+ OTHER_TRANSACTION_PREFIX = 'OtherTransaction/'
TASK_PREFIX = "#{OTHER_TRANSACTION_PREFIX}Background/"
RAKE_PREFIX = "#{OTHER_TRANSACTION_PREFIX}Rake/"
MESSAGE_PREFIX = "#{OTHER_TRANSACTION_PREFIX}Message/"
@@ -37,21 +37,21 @@ class Transaction
WEB_TRANSACTION_CATEGORIES = [:web, :controller, :uri, :rack, :sinatra, :grape, :middleware, :action_cable].freeze
- MIDDLEWARE_SUMMARY_METRICS = ["Middleware/all"].freeze
- WEB_SUMMARY_METRIC = "HttpDispatcher"
+ MIDDLEWARE_SUMMARY_METRICS = ['Middleware/all'].freeze
+ WEB_SUMMARY_METRIC = 'HttpDispatcher'
OTHER_SUMMARY_METRIC = "#{OTHER_TRANSACTION_PREFIX}all"
- QUEUE_TIME_METRIC = "WebFrontend/QueueTime"
+ QUEUE_TIME_METRIC = 'WebFrontend/QueueTime'
- APDEX_S = "S"
- APDEX_T = "T"
- APDEX_F = "F"
- APDEX_ALL_METRIC = "ApdexAll"
- APDEX_METRIC = "Apdex"
- APDEX_OTHER_METRIC = "ApdexOther"
- APDEX_TXN_METRIC_PREFIX = "Apdex/"
- APDEX_OTHER_TXN_METRIC_PREFIX = "ApdexOther/Transaction/"
+ APDEX_S = 'S'
+ APDEX_T = 'T'
+ APDEX_F = 'F'
+ APDEX_ALL_METRIC = 'ApdexAll'
+ APDEX_METRIC = 'Apdex'
+ APDEX_OTHER_METRIC = 'ApdexOther'
+ APDEX_TXN_METRIC_PREFIX = 'Apdex/'
+ APDEX_OTHER_TXN_METRIC_PREFIX = 'ApdexOther/Transaction/'
- JRUBY_CPU_TIME_ERROR = "Error calculating JRuby CPU Time"
+ JRUBY_CPU_TIME_ERROR = 'Error calculating JRuby CPU Time'
# A Time instance for the start time, never nil
attr_accessor :start_time
@@ -155,7 +155,7 @@ def self.recording_web_transaction? # THREAD_LOCAL_ACCESS
NewRelic::Agent.record_api_supportability_metric(:recording_web_transaction?)
txn = tl_current
- txn && txn.recording_web_transaction?
+ txn&.recording_web_transaction?
end
def self.apdex_bucket(duration, failed, apdex_t)
@@ -181,20 +181,21 @@ def self.add_agent_attribute(key, value, default_destinations)
def add_agent_attribute(key, value, default_destinations)
@attributes.add_agent_attribute(key, value, default_destinations)
- current_segment.add_agent_attribute(key, value) if current_segment
+ # the following line needs else branch coverage
+ current_segment.add_agent_attribute(key, value) if current_segment # rubocop:disable Style/SafeNavigation
end
def self.merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
if txn = tl_current
txn.merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
else
- NewRelic::Agent.logger.debug("Attempted to merge untrusted attributes without transaction")
+ NewRelic::Agent.logger.debug('Attempted to merge untrusted attributes without transaction')
end
end
def merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
@attributes.merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
- current_segment.merge_untrusted_agent_attributes(attributes, prefix, default_destinations) if current_segment
+ current_segment&.merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
end
@@java_classes_loaded = false
@@ -209,7 +210,7 @@ def merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
end
end
- def initialize(category, options)
+ def initialize(category, options) # rubocop:disable Metrics/AbcSize
@nesting_max_depth = 0
@current_segment_by_thread = {}
@current_segment_lock = Mutex.new
@@ -309,15 +310,15 @@ def priority
end
def referer
- @request_attributes && @request_attributes.referer
+ @request_attributes&.referer
end
def request_path
- @request_attributes && @request_attributes.request_path
+ @request_attributes&.request_path
end
def request_port
- @request_attributes && @request_attributes.port
+ @request_attributes&.port
end
# This transaction-local hash may be used as temporary storage by
@@ -533,7 +534,7 @@ def finish
commit!(initial_segment.name) unless @ignore_this_transaction
rescue => e
- NewRelic::Agent.logger.error("Exception during Transaction#finish", e)
+ NewRelic::Agent.logger.error('Exception during Transaction#finish', e)
nil
ensure
state.reset
@@ -594,9 +595,7 @@ def assign_agent_attributes
add_agent_attribute(:'response.headers.contentType', response_content_type, default_destinations)
end
- if @request_attributes
- @request_attributes.assign_agent_attributes(self)
- end
+ @request_attributes&.assign_agent_attributes(self)
display_host = Agent.config[:'process_host.display_name']
unless display_host == NewRelic::Agent::Hostname.get
@@ -735,15 +734,19 @@ def merge_metrics
def record_exceptions
error_recorded = false
@exceptions.each do |exception, options|
- options[:uri] ||= request_path if request_path
- options[:port] = request_port if request_port
- options[:metric] = best_name
- options[:attributes] = @attributes
-
- span_id = options.delete(:span_id)
- error_recorded = !!agent.error_collector.notice_error(exception, options, span_id) || error_recorded
+ error_recorded = record_exception(exception, options, error_recorded)
end
- payload[:error] = error_recorded if payload
+ payload&.[]=(:error, error_recorded)
+ end
+
+ def record_exception(exception, options, error_recorded)
+ options[:uri] ||= request_path if request_path
+ options[:port] = request_port if request_port
+ options[:metric] = best_name
+ options[:attributes] = @attributes
+
+ span_id = options.delete(:span_id)
+ !!agent.error_collector.notice_error(exception, options, span_id) || error_recorded
end
# Do not call this. Invoke the class method instead.
diff --git a/lib/new_relic/agent/transaction/abstract_segment.rb b/lib/new_relic/agent/transaction/abstract_segment.rb
index 92e677ea1e..072348aaf3 100644
--- a/lib/new_relic/agent/transaction/abstract_segment.rb
+++ b/lib/new_relic/agent/transaction/abstract_segment.rb
@@ -56,7 +56,7 @@ def start
@start_time ||= Process.clock_gettime(Process::CLOCK_REALTIME)
return unless transaction
- parent.child_start(self) if parent
+ parent&.child_start(self)
end
def finish
@@ -228,7 +228,7 @@ def child_complete(segment)
if finished?
transaction.async = true
- parent.descendant_complete(self, segment) if parent
+ parent&.descendant_complete(self, segment)
end
end
@@ -262,19 +262,19 @@ def add_child_timing(segment)
def force_finish
finish
- NewRelic::Agent.logger.warn("Segment: #{name} was unfinished at " \
- "the end of transaction. Timing information for this segment's" \
- "parent #{parent.name} in #{transaction.best_name} may be inaccurate.")
+ NewRelic::Agent.logger.send(transaction.async? ? :debug : :warn, "Segment: #{name} was unfinished at " \
+ "the end of transaction. Timing information for this segment's " \
+ "parent #{parent&.name} in #{transaction.best_name} may be inaccurate.")
end
def run_complete_callbacks
segment_complete
- parent.child_complete(self) if parent
+ parent&.child_complete(self)
transaction.segment_complete(self)
end
def record_metrics
- raise NotImplementedError, "Subclasses must implement record_metrics"
+ raise NotImplementedError, 'Subclasses must implement record_metrics'
end
# callback for subclasses to override
diff --git a/lib/new_relic/agent/transaction/datastore_segment.rb b/lib/new_relic/agent/transaction/datastore_segment.rb
index d6c529a7d1..01d119b83c 100644
--- a/lib/new_relic/agent/transaction/datastore_segment.rb
+++ b/lib/new_relic/agent/transaction/datastore_segment.rb
@@ -24,7 +24,7 @@ def initialize(product, operation, collection = nil, host = nil, port_path_or_id
@nosql_statement = nil
@record_sql = true
set_instance_info(host, port_path_or_id)
- @database_name = database_name ? database_name.to_s : nil
+ @database_name = database_name&.to_s
super(Datastores::MetricHelper.scoped_metric_for(product, operation, collection),
nil,
start_time)
diff --git a/lib/new_relic/agent/transaction/distributed_tracer.rb b/lib/new_relic/agent/transaction/distributed_tracer.rb
index 198428efbe..f14a2bd88d 100644
--- a/lib/new_relic/agent/transaction/distributed_tracer.rb
+++ b/lib/new_relic/agent/transaction/distributed_tracer.rb
@@ -35,7 +35,7 @@ def accept_incoming_request(request, transport_type = nil)
end
def caller_transport_type
- @caller_transport_type ||= "Unknown"
+ @caller_transport_type ||= 'Unknown'
end
def accept_transport_type_from_api(value)
@@ -68,8 +68,9 @@ def append_payload(payload)
)
end
- def log_request_headers(headers, direction = "OUTGOING")
- NewRelic::Agent.logger.debug("#{direction} REQUEST HEADERS: #{headers}")
+ def log_request_headers(headers, direction = 'OUTGOING')
+ printed_headers = headers.is_a?(NewRelic::Agent::HTTPClients::AbstractRequest) ? headers.headers : headers
+ NewRelic::Agent.logger.debug("#{direction} REQUEST HEADERS: #{printed_headers}")
end
def insert_headers(headers)
@@ -82,12 +83,12 @@ def insert_headers(headers)
end
def consume_message_headers(headers, tracer_state, transport_type)
- log_request_headers(headers, "INCOMING")
+ log_request_headers(headers, 'INCOMING')
consume_message_distributed_tracing_headers(headers, transport_type)
consume_message_cross_app_tracing_headers(headers, tracer_state)
consume_message_synthetics_headers(headers)
rescue => e
- NewRelic::Agent.logger.error("Error in consume_message_headers", e)
+ NewRelic::Agent.logger.error('Error in consume_message_headers', e)
end
def assign_intrinsics
@@ -135,7 +136,7 @@ def consume_message_synthetics_headers(headers)
transaction.synthetics_payload = incoming_payload
end
rescue => e
- NewRelic::Agent.logger.error("Error in consume_message_synthetics_header", e)
+ NewRelic::Agent.logger.error('Error in consume_message_synthetics_header', e)
end
def consume_message_distributed_tracing_headers(headers, transport_type)
diff --git a/lib/new_relic/agent/transaction/distributed_tracing.rb b/lib/new_relic/agent/transaction/distributed_tracing.rb
index cb0e7f2dc5..e022e122eb 100644
--- a/lib/new_relic/agent/transaction/distributed_tracing.rb
+++ b/lib/new_relic/agent/transaction/distributed_tracing.rb
@@ -13,7 +13,7 @@ module DistributedTracing
attr_accessor :distributed_trace_payload
attr_writer :distributed_trace_payload_created
- SUPPORTABILITY_DISTRIBUTED_TRACE = "Supportability/DistributedTrace"
+ SUPPORTABILITY_DISTRIBUTED_TRACE = 'Supportability/DistributedTrace'
CREATE_PREFIX = "#{SUPPORTABILITY_DISTRIBUTED_TRACE}/CreatePayload"
ACCEPT_PREFIX = "#{SUPPORTABILITY_DISTRIBUTED_TRACE}/AcceptPayload"
IGNORE_PREFIX = "#{ACCEPT_PREFIX}/Ignored"
@@ -30,10 +30,10 @@ module DistributedTracing
IGNORE_ACCEPT_MAJOR_VERSION_METRIC = "#{IGNORE_PREFIX}/MajorVersion"
IGNORE_ACCEPT_UNTRUSTED_ACCOUNT_METRIC = "#{IGNORE_PREFIX}/UntrustedAccount"
- LBRACE = "{"
+ LBRACE = '{'
NULL_PAYLOAD = 'null'
- NEWRELIC_TRACE_KEY = "HTTP_NEWRELIC"
+ NEWRELIC_TRACE_KEY = 'HTTP_NEWRELIC'
def accept_distributed_tracing_incoming_request(request)
return unless Agent.config[:'distributed_tracing.enabled']
@@ -55,7 +55,7 @@ def create_distributed_trace_payload
payload
rescue => e
NewRelic::Agent.increment_metric(CREATE_EXCEPTION_METRIC)
- NewRelic::Agent.logger.warn("Failed to create distributed trace payload", e)
+ NewRelic::Agent.logger.warn('Failed to create distributed trace payload', e)
nil
end
@@ -75,7 +75,7 @@ def accept_distributed_trace_payload(payload)
true
rescue => e
NewRelic::Agent.increment_metric(ACCEPT_EXCEPTION_METRIC)
- NewRelic::Agent.logger.warn("Failed to accept distributed trace payload", e)
+ NewRelic::Agent.logger.warn('Failed to accept distributed trace payload', e)
false
end
@@ -114,7 +114,7 @@ def decode_payload(payload)
decoded
rescue => e
NewRelic::Agent.increment_metric(ACCEPT_PARSE_EXCEPTION_METRIC)
- NewRelic::Agent.logger.warn("Error parsing distributed trace payload", e)
+ NewRelic::Agent.logger.warn('Error parsing distributed trace payload', e)
nil
end
diff --git a/lib/new_relic/agent/transaction/external_request_segment.rb b/lib/new_relic/agent/transaction/external_request_segment.rb
index d480e39676..303b0d7a76 100644
--- a/lib/new_relic/agent/transaction/external_request_segment.rb
+++ b/lib/new_relic/agent/transaction/external_request_segment.rb
@@ -16,10 +16,10 @@ class ExternalRequestSegment < Segment
NR_SYNTHETICS_HEADER = 'X-NewRelic-Synthetics'
APP_DATA_KEY = 'NewRelicAppData'
- EXTERNAL_ALL = "External/all"
- EXTERNAL_ALL_WEB = "External/allWeb"
- EXTERNAL_ALL_OTHER = "External/allOther"
- MISSING_STATUS_CODE = "MissingHTTPStatusCode"
+ EXTERNAL_ALL = 'External/all'
+ EXTERNAL_ALL_WEB = 'External/allWeb'
+ EXTERNAL_ALL_OTHER = 'External/allOther'
+ MISSING_STATUS_CODE = 'MissingHTTPStatusCode'
attr_reader :library, :uri, :procedure, :http_status_code
attr_writer :record_agent_attributes
@@ -62,14 +62,14 @@ def record_agent_attributes?
# @api public
def add_request_headers(request)
process_host_header(request)
- synthetics_header = transaction && transaction.raw_synthetics_header
+ synthetics_header = transaction&.raw_synthetics_header
insert_synthetics_header(request, synthetics_header) if synthetics_header
return unless record_metrics?
transaction.distributed_tracer.insert_headers(request)
rescue => e
- NewRelic::Agent.logger.error("Error in add_request_headers", e)
+ NewRelic::Agent.logger.error('Error in add_request_headers', e)
end
# This method extracts app data from an external response if present. If
@@ -92,10 +92,10 @@ def read_response_headers(response)
@app_data = data
update_segment_name
else
- NewRelic::Agent.logger.debug("External segment response has invalid cross_app_id")
+ NewRelic::Agent.logger.debug('External segment response has invalid cross_app_id')
end
rescue => e
- NewRelic::Agent.logger.error("Error in read_response_headers", e)
+ NewRelic::Agent.logger.error('Error in read_response_headers', e)
end
def cross_app_request? # :nodoc:
@@ -154,7 +154,7 @@ def get_request_metadata
end
rescue => e
- NewRelic::Agent.logger.error("error during get_request_metadata", e)
+ NewRelic::Agent.logger.error('error during get_request_metadata', e)
end
# Process obfuscated +String+ sent from a called application that is also running a New Relic agent and
@@ -176,13 +176,13 @@ def process_response_metadata(response_metadata)
@app_data = app_data
update_segment_name
else
- NewRelic::Agent.logger.error("error processing response metadata: invalid/non-trusted ID")
+ NewRelic::Agent.logger.error('error processing response metadata: invalid/non-trusted ID')
end
end
nil
rescue => e
- NewRelic::Agent.logger.error("error during process_response_metadata", e)
+ NewRelic::Agent.logger.error('error during process_response_metadata', e)
end
def record_metrics
diff --git a/lib/new_relic/agent/transaction/message_broker_segment.rb b/lib/new_relic/agent/transaction/message_broker_segment.rb
index 32fbc98513..4d0d145ff1 100644
--- a/lib/new_relic/agent/transaction/message_broker_segment.rb
+++ b/lib/new_relic/agent/transaction/message_broker_segment.rb
@@ -91,7 +91,7 @@ def transaction_assigned
transaction.distributed_tracer.log_request_headers(headers)
end
rescue => e
- NewRelic::Agent.logger.error("Error during message header processing", e)
+ NewRelic::Agent.logger.error('Error during message header processing', e)
end
end
end
diff --git a/lib/new_relic/agent/transaction/request_attributes.rb b/lib/new_relic/agent/transaction/request_attributes.rb
index 45318b7600..ad68d27be0 100644
--- a/lib/new_relic/agent/transaction/request_attributes.rb
+++ b/lib/new_relic/agent/transaction/request_attributes.rb
@@ -11,7 +11,7 @@ class RequestAttributes
attr_reader :request_path, :referer, :accept, :content_length, :content_type,
:host, :port, :user_agent, :request_method
- HTTP_ACCEPT_HEADER_KEY = "HTTP_ACCEPT".freeze
+ HTTP_ACCEPT_HEADER_KEY = 'HTTP_ACCEPT'.freeze
def initialize(request)
@request_path = path_from_request(request)
@@ -85,7 +85,7 @@ def referer_from_request(request)
# rails construct the PATH_INFO enviroment variable improperly and we're generally
# being defensive.
- ROOT_PATH = "/".freeze
+ ROOT_PATH = '/'.freeze
def path_from_request(request)
path = attribute_from_request(request, :path) || ''
diff --git a/lib/new_relic/agent/transaction/segment.rb b/lib/new_relic/agent/transaction/segment.rb
index 4cdda45d90..b8b1f7a9dc 100644
--- a/lib/new_relic/agent/transaction/segment.rb
+++ b/lib/new_relic/agent/transaction/segment.rb
@@ -32,7 +32,7 @@ def self.merge_untrusted_agent_attributes(attributes, prefix, default_destinatio
if segment = NewRelic::Agent::Tracer.current_segment
segment.merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
else
- NewRelic::Agent.logger.debug("Attempted to merge untrusted attributes without segment")
+ NewRelic::Agent.logger.debug('Attempted to merge untrusted attributes without segment')
end
end
diff --git a/lib/new_relic/agent/transaction/synthetics_sample_buffer.rb b/lib/new_relic/agent/transaction/synthetics_sample_buffer.rb
index 1d0631013f..5b384ec156 100644
--- a/lib/new_relic/agent/transaction/synthetics_sample_buffer.rb
+++ b/lib/new_relic/agent/transaction/synthetics_sample_buffer.rb
@@ -13,7 +13,7 @@ def capacity
end
def allow_sample?(sample)
- sample.synthetics_resource_id != nil
+ !sample.synthetics_resource_id.nil?
end
def truncate_samples
diff --git a/lib/new_relic/agent/transaction/trace.rb b/lib/new_relic/agent/transaction/trace.rb
index 6e3a2fda10..2052a2818d 100644
--- a/lib/new_relic/agent/transaction/trace.rb
+++ b/lib/new_relic/agent/transaction/trace.rb
@@ -14,7 +14,7 @@ class FinishedTraceError < StandardError; end
attr_accessor :transaction_name, :guid, :attributes,
:node_count, :finished, :threshold, :profile
- ROOT = "ROOT".freeze
+ ROOT = 'ROOT'.freeze
def initialize(start_time)
@start_time = start_time
diff --git a/lib/new_relic/agent/transaction/trace_context.rb b/lib/new_relic/agent/transaction/trace_context.rb
index 054ebec626..26b267161f 100644
--- a/lib/new_relic/agent/transaction/trace_context.rb
+++ b/lib/new_relic/agent/transaction/trace_context.rb
@@ -20,7 +20,7 @@ def trace_state_entry_key
end
end
- SUPPORTABILITY_PREFIX = "Supportability/TraceContext"
+ SUPPORTABILITY_PREFIX = 'Supportability/TraceContext'
CREATE_PREFIX = "#{SUPPORTABILITY_PREFIX}/Create"
ACCEPT_PREFIX = "#{SUPPORTABILITY_PREFIX}/Accept"
TRACESTATE_PREFIX = "#{SUPPORTABILITY_PREFIX}/TraceState"
@@ -73,7 +73,7 @@ def insert_trace_context_header(header, format = NewRelic::FORMAT_NON_RACK)
true
rescue Exception => e
NewRelic::Agent.increment_metric(CREATE_EXCEPTION_METRIC)
- NewRelic::Agent.logger.warn("Failed to create trace context payload", e)
+ NewRelic::Agent.logger.warn('Failed to create trace context payload', e)
false
end
@@ -95,7 +95,7 @@ def create_trace_state
def create_trace_state_payload
unless Agent.config[:'distributed_tracing.enabled']
- NewRelic::Agent.logger.warn("Not configured to create WC3 trace context payload")
+ NewRelic::Agent.logger.warn('Not configured to create WC3 trace context payload')
return
end
@@ -144,7 +144,7 @@ def accept_trace_context(header_data)
true
rescue => e
NewRelic::Agent.increment_metric(ACCEPT_EXCEPTION_METRIC)
- NewRelic::Agent.logger.warn("Failed to accept trace context payload", e)
+ NewRelic::Agent.logger.warn('Failed to accept trace context payload', e)
false
end
diff --git a/lib/new_relic/agent/transaction/trace_node.rb b/lib/new_relic/agent/transaction/trace_node.rb
index 419da176b9..c0f929fbf4 100644
--- a/lib/new_relic/agent/transaction/trace_node.rb
+++ b/lib/new_relic/agent/transaction/trace_node.rb
@@ -58,7 +58,7 @@ def path_string
end
def to_s_compact
- str = String.new('')
+ str = +''
str << metric_name
if children.any?
str << "{#{children.map { |cs| cs.to_s_compact }.join(',')}}"
@@ -67,9 +67,9 @@ def to_s_compact
end
def to_debug_str(depth)
- tab = String.new(' ') * depth
+ tab = (+' ') * depth
s = tab.clone
- s << ">> #{'%3i ms' % (@entry_timestamp * 1000)} [#{self.class.name.split("::").last}] #{metric_name} \n"
+ s << ">> #{'%3i ms' % (@entry_timestamp * 1000)} [#{self.class.name.split('::').last}] #{metric_name} \n"
unless params.empty?
params.each do |k, v|
s << "#{tab} -#{'%-16s' % k}: #{v.to_s[0..80]}\n"
@@ -136,10 +136,8 @@ def [](key)
def each_node(&block)
yield(self)
- if @children
- @children.each do |node|
- node.each_node(&block)
- end
+ @children&.each do |node|
+ node.each_node(&block)
end
end
@@ -149,11 +147,14 @@ def each_node_with_nest_tracking(&block)
summary = yield(self)
summary.current_nest_count += 1 if summary
+ # no then branch coverage
+ # rubocop:disable Style/SafeNavigation
if @children
@children.each do |node|
node.each_node_with_nest_tracking(&block)
end
end
+ # rubocop:enable Style/SafeNavigation
summary.current_nest_count -= 1 if summary
end
diff --git a/lib/new_relic/agent/transaction/tracing.rb b/lib/new_relic/agent/transaction/tracing.rb
index 5166455920..1ed62d462c 100644
--- a/lib/new_relic/agent/transaction/tracing.rb
+++ b/lib/new_relic/agent/transaction/tracing.rb
@@ -52,8 +52,8 @@ def finalize_segments
segments.each { |s| s.finalize }
end
- WEB_TRANSACTION_TOTAL_TIME = "WebTransactionTotalTime".freeze
- OTHER_TRANSACTION_TOTAL_TIME = "OtherTransactionTotalTime".freeze
+ WEB_TRANSACTION_TOTAL_TIME = 'WebTransactionTotalTime'.freeze
+ OTHER_TRANSACTION_TOTAL_TIME = 'OtherTransactionTotalTime'.freeze
def record_total_time_metrics
total_time_metric = if recording_web_transaction?
diff --git a/lib/new_relic/agent/transaction/transaction_sample_buffer.rb b/lib/new_relic/agent/transaction/transaction_sample_buffer.rb
index 88cf33b3d8..9700a90449 100644
--- a/lib/new_relic/agent/transaction/transaction_sample_buffer.rb
+++ b/lib/new_relic/agent/transaction/transaction_sample_buffer.rb
@@ -63,7 +63,7 @@ def full?
#
# This value will be forcibly capped by the max_capacity
def capacity
- raise NotImplementedError.new("TransactionSampleBuffer subclasses must provide a capacity override")
+ raise NotImplementedError.new('TransactionSampleBuffer subclasses must provide a capacity override')
end
# Apply hard upper limit to the capacity to prevent users from
diff --git a/lib/new_relic/agent/transaction_error_primitive.rb b/lib/new_relic/agent/transaction_error_primitive.rb
index 5b00810cf2..38333ef533 100644
--- a/lib/new_relic/agent/transaction_error_primitive.rb
+++ b/lib/new_relic/agent/transaction_error_primitive.rb
@@ -28,11 +28,11 @@ module TransactionErrorPrimitive
SAMPLED_KEY = 'sampled'.freeze
GUID_KEY = 'nr.transactionGuid'.freeze
REFERRING_TRANSACTION_GUID_KEY = 'nr.referringTransactionGuid'.freeze
- SYNTHETICS_RESOURCE_ID_KEY = "nr.syntheticsResourceId".freeze
- SYNTHETICS_JOB_ID_KEY = "nr.syntheticsJobId".freeze
- SYNTHETICS_MONITOR_ID_KEY = "nr.syntheticsMonitorId".freeze
- PRIORITY_KEY = "priority".freeze
- SPAN_ID_KEY = "spanId".freeze
+ SYNTHETICS_RESOURCE_ID_KEY = 'nr.syntheticsResourceId'.freeze
+ SYNTHETICS_JOB_ID_KEY = 'nr.syntheticsJobId'.freeze
+ SYNTHETICS_MONITOR_ID_KEY = 'nr.syntheticsMonitorId'.freeze
+ PRIORITY_KEY = 'priority'.freeze
+ SPAN_ID_KEY = 'spanId'.freeze
def create(noticed_error, payload, span_id)
[
diff --git a/lib/new_relic/agent/transaction_event_aggregator.rb b/lib/new_relic/agent/transaction_event_aggregator.rb
index 64e0cc9f9a..39000404b7 100644
--- a/lib/new_relic/agent/transaction_event_aggregator.rb
+++ b/lib/new_relic/agent/transaction_event_aggregator.rb
@@ -18,7 +18,7 @@ class TransactionEventAggregator < EventAggregator
def record(priority: nil, event: nil, &blk)
unless event || priority && blk
- raise ArgumentError, "Expected priority and block, or event"
+ raise ArgumentError, 'Expected priority and block, or event'
end
return unless enabled?
@@ -38,7 +38,7 @@ def after_harvest(metadata)
end
def record_sampling_rate(metadata) # THREAD_LOCAL_ACCESS
- NewRelic::Agent.logger.debug("Sampled %d / %d (%.1f %%) requests this cycle, %d / %d (%.1f %%) since startup" % [
+ NewRelic::Agent.logger.debug('Sampled %d / %d (%.1f %%) requests this cycle, %d / %d (%.1f %%) since startup' % [
metadata[:captured],
metadata[:seen],
(metadata[:captured].to_f / metadata[:seen] * 100.0),
@@ -48,8 +48,8 @@ def record_sampling_rate(metadata) # THREAD_LOCAL_ACCESS
])
engine = NewRelic::Agent.instance.stats_engine
- engine.tl_record_supportability_metric_count("TransactionEventAggregator/requests", metadata[:seen])
- engine.tl_record_supportability_metric_count("TransactionEventAggregator/samples", metadata[:captured])
+ engine.tl_record_supportability_metric_count('TransactionEventAggregator/requests', metadata[:seen])
+ engine.tl_record_supportability_metric_count('TransactionEventAggregator/samples', metadata[:captured])
end
end
end
diff --git a/lib/new_relic/agent/transaction_event_primitive.rb b/lib/new_relic/agent/transaction_event_primitive.rb
index f430b8149e..f1fc99a0aa 100644
--- a/lib/new_relic/agent/transaction_event_primitive.rb
+++ b/lib/new_relic/agent/transaction_event_primitive.rb
@@ -35,9 +35,9 @@ module TransactionEventPrimitive
CAT_REFERRING_PATH_HASH_KEY = 'nr.referringPathHash'
CAT_ALTERNATE_PATH_HASHES_KEY = 'nr.alternatePathHashes'
APDEX_PERF_ZONE_KEY = 'nr.apdexPerfZone'
- SYNTHETICS_RESOURCE_ID_KEY = "nr.syntheticsResourceId"
- SYNTHETICS_JOB_ID_KEY = "nr.syntheticsJobId"
- SYNTHETICS_MONITOR_ID_KEY = "nr.syntheticsMonitorId"
+ SYNTHETICS_RESOURCE_ID_KEY = 'nr.syntheticsResourceId'
+ SYNTHETICS_JOB_ID_KEY = 'nr.syntheticsJobId'
+ SYNTHETICS_MONITOR_ID_KEY = 'nr.syntheticsMonitorId'
def create(payload)
intrinsics = {
diff --git a/lib/new_relic/agent/transaction_sampler.rb b/lib/new_relic/agent/transaction_sampler.rb
index a4100fe383..d9614a6c3d 100644
--- a/lib/new_relic/agent/transaction_sampler.rb
+++ b/lib/new_relic/agent/transaction_sampler.rb
@@ -34,13 +34,13 @@ def initialize
threshold = Agent.config[:'transaction_tracer.transaction_threshold']
::NewRelic::Agent.logger.debug("Transaction tracing threshold is #{threshold} seconds.")
else
- ::NewRelic::Agent.logger.debug("Transaction traces will not be sent to the New Relic service.")
+ ::NewRelic::Agent.logger.debug('Transaction traces will not be sent to the New Relic service.')
end
end
Agent.config.register_callback(:'transaction_tracer.record_sql') do |config|
if config == 'raw'
- ::NewRelic::Agent.logger.warn("Agent is configured to send raw SQL to the service")
+ ::NewRelic::Agent.logger.warn('Agent is configured to send raw SQL to the service')
end
end
end
@@ -81,7 +81,7 @@ def prepare_samples(samples)
begin
sample.prepare_to_send!
rescue => e
- NewRelic::Agent.logger.error("Failed to prepare transaction trace. Error: ", e)
+ NewRelic::Agent.logger.error('Failed to prepare transaction trace. Error: ', e)
false
else
true
diff --git a/lib/new_relic/agent/transaction_time_aggregator.rb b/lib/new_relic/agent/transaction_time_aggregator.rb
index bf19314d7a..c0e445ab3b 100644
--- a/lib/new_relic/agent/transaction_time_aggregator.rb
+++ b/lib/new_relic/agent/transaction_time_aggregator.rb
@@ -101,7 +101,8 @@ def current_thread
def thread_is_alive?(thread_id)
thread = thread_by_id(thread_id)
- thread && thread.alive?
+ # needs else branch coverage
+ thread && thread.alive? # rubocop:disable Style/SafeNavigation
rescue StandardError
false
end
@@ -144,10 +145,13 @@ def transaction_time_in_thread(timestamp, thread_id, entry)
elapsed
end
+ # this method has no test coverage
def log_missing_elapsed_transaction_time
- transaction_name = Tracer.current_transaction &&
+ # rubocop:disable Style/SafeNavigation
+ transaction_name = transaction_name = Tracer.current_transaction &&
Tracer.current_transaction.best_name ||
- "unknown"
+ 'unknown'
+ # rubocop:enable Style/SafeNavigation
NewRelic::Agent.logger.warn("Unable to calculate elapsed transaction time for #{transaction_name}")
end
end
diff --git a/lib/new_relic/agent/utilization/aws.rb b/lib/new_relic/agent/utilization/aws.rb
index 0856ac46b4..8ecb2532b3 100644
--- a/lib/new_relic/agent/utilization/aws.rb
+++ b/lib/new_relic/agent/utilization/aws.rb
@@ -37,7 +37,7 @@ def imds_token
end
end
- vendor_name "aws"
+ vendor_name 'aws'
endpoint "#{IMDS_BASE_URL}/dynamic/instance-identity/document"
keys IMDS_KEYS
headers 'X-aws-ec2-metadata-token' => -> { imds_token }
diff --git a/lib/new_relic/agent/utilization/azure.rb b/lib/new_relic/agent/utilization/azure.rb
index 2ff289ef7a..cf47c2a617 100644
--- a/lib/new_relic/agent/utilization/azure.rb
+++ b/lib/new_relic/agent/utilization/azure.rb
@@ -6,9 +6,9 @@ module NewRelic
module Agent
module Utilization
class Azure < Vendor
- vendor_name "azure"
- endpoint "http://169.254.169.254/metadata/instance/compute?api-version=2017-03-01"
- headers "Metadata" => "true"
+ vendor_name 'azure'
+ endpoint 'http://169.254.169.254/metadata/instance/compute?api-version=2017-03-01'
+ headers 'Metadata' => 'true'
keys %w[vmId name vmSize location]
key_transforms :to_sym
end
diff --git a/lib/new_relic/agent/utilization/gcp.rb b/lib/new_relic/agent/utilization/gcp.rb
index a578c9f63a..06d67cac29 100644
--- a/lib/new_relic/agent/utilization/gcp.rb
+++ b/lib/new_relic/agent/utilization/gcp.rb
@@ -8,9 +8,9 @@ module NewRelic
module Agent
module Utilization
class GCP < Vendor
- vendor_name "gcp"
- endpoint "http://metadata.google.internal/computeMetadata/v1/instance/?recursive=true"
- headers "Metadata-Flavor" => "Google"
+ vendor_name 'gcp'
+ endpoint 'http://metadata.google.internal/computeMetadata/v1/instance/?recursive=true'
+ headers 'Metadata-Flavor' => 'Google'
keys %w[id machineType name zone]
key_transforms :to_sym
diff --git a/lib/new_relic/agent/utilization/pcf.rb b/lib/new_relic/agent/utilization/pcf.rb
index a0aad26fb3..81068488a7 100644
--- a/lib/new_relic/agent/utilization/pcf.rb
+++ b/lib/new_relic/agent/utilization/pcf.rb
@@ -8,7 +8,7 @@ module NewRelic
module Agent
module Utilization
class PCF < Vendor
- vendor_name "pcf"
+ vendor_name 'pcf'
keys %w[CF_INSTANCE_GUID CF_INSTANCE_IP MEMORY_LIMIT]
key_transforms [:downcase, :to_sym]
diff --git a/lib/new_relic/agent/utilization/vendor.rb b/lib/new_relic/agent/utilization/vendor.rb
index 0271adb72d..bceac3932e 100644
--- a/lib/new_relic/agent/utilization/vendor.rb
+++ b/lib/new_relic/agent/utilization/vendor.rb
@@ -133,7 +133,7 @@ def valid_length?(value)
def valid_chars?(value)
value.each_char do |ch|
- next if ch =~ VALID_CHARS
+ next if VALID_CHARS.match?(ch)
code_point = ch[0].ord # this works in Ruby 1.8.7 - 2.1.2
next if code_point >= 0x80
diff --git a/lib/new_relic/agent/vm/monotonic_gc_profiler.rb b/lib/new_relic/agent/vm/monotonic_gc_profiler.rb
index f09f322454..a70bfac0fc 100644
--- a/lib/new_relic/agent/vm/monotonic_gc_profiler.rb
+++ b/lib/new_relic/agent/vm/monotonic_gc_profiler.rb
@@ -34,7 +34,7 @@ def total_time_s
end
else
NewRelic::Agent.logger.log_once(:warn, :gc_profiler_disabled,
- "Tried to measure GC time, but GC::Profiler was not enabled.")
+ 'Tried to measure GC time, but GC::Profiler was not enabled.')
end
@total_time_s
diff --git a/lib/new_relic/agent/vm/mri_vm.rb b/lib/new_relic/agent/vm/mri_vm.rb
index 8eb595b730..93dedba5f0 100644
--- a/lib/new_relic/agent/vm/mri_vm.rb
+++ b/lib/new_relic/agent/vm/mri_vm.rb
@@ -82,18 +82,19 @@ def gather_thread_stats(snap)
def supports?(key)
case key
- when :gc_runs, :total_allocated_object, :heap_live, :heap_free, :thread_count
+ when :gc_runs,
+ :total_allocated_object,
+ :heap_live,
+ :heap_free,
+ :thread_count,
+ :major_gc_count,
+ :minor_gc_count,
+ :constant_cache_invalidations
true
when :gc_total_time
NewRelic::LanguageSupport.gc_profiler_enabled?
- when :major_gc_count
- RUBY_VERSION >= '2.1.0'
- when :minor_gc_count
- RUBY_VERSION >= '2.1.0'
when :method_cache_invalidations
- RUBY_VERSION >= '2.1.0' && RUBY_VERSION < '3.0.0'
- when :constant_cache_invalidations
- RUBY_VERSION >= '2.1.0'
+ RUBY_VERSION < '3.0.0'
when :constant_cache_misses
RUBY_VERSION >= '3.2.0'
else
diff --git a/lib/new_relic/agent/worker_loop.rb b/lib/new_relic/agent/worker_loop.rb
index f4454296b5..5a47875c6b 100644
--- a/lib/new_relic/agent/worker_loop.rb
+++ b/lib/new_relic/agent/worker_loop.rb
@@ -88,7 +88,7 @@ def run_task
raise
rescue => e
# Don't blow out the stack for anything that hasn't already propagated
- ::NewRelic::Agent.logger.error("Error running task in Agent Worker Loop:", e)
+ ::NewRelic::Agent.logger.error('Error running task in Agent Worker Loop:', e)
end
end
end
diff --git a/lib/new_relic/cli/command.rb b/lib/new_relic/cli/command.rb
index d01ba47989..099dc1ea78 100644
--- a/lib/new_relic/cli/command.rb
+++ b/lib/new_relic/cli/command.rb
@@ -38,7 +38,7 @@ def initialize(command_line_args)
else
# parse command line args. Throw an exception on a bad arg.
@options = options do |opts|
- opts.on("-h", "Show this help") { raise CommandFailure, opts.to_s }
+ opts.on('-h', 'Show this help') { raise CommandFailure, opts.to_s }
end
@leftover = @options.parse(command_line_args)
end
@@ -60,11 +60,11 @@ def self.run
extra = []
options = ARGV.options do |opts|
script_name = File.basename($0)
- if script_name =~ /newrelic_cmd$/
+ if /newrelic_cmd$/.match?(script_name)
$stdout.puts "warning: the 'newrelic_cmd' script has been renamed 'newrelic'"
script_name = 'newrelic'
end
- opts.banner = "Usage: #{script_name} [ #{@command_names.join(" | ")} ] [options]"
+ opts.banner = "Usage: #{script_name} [ #{@command_names.join(' | ')} ] [options]"
opts.separator("use '#{script_name} -h' to see detailed command options")
opts
end
diff --git a/lib/new_relic/cli/commands/deployments.rb b/lib/new_relic/cli/commands/deployments.rb
index 2192de0b7d..a191d1dd92 100644
--- a/lib/new_relic/cli/commands/deployments.rb
+++ b/lib/new_relic/cli/commands/deployments.rb
@@ -16,7 +16,7 @@
class NewRelic::Cli::Deployments < NewRelic::Cli::Command
attr_reader :control
- def self.command; "deployments"; end
+ def self.command; 'deployments'; end
# Initialize the deployment uploader with command line args.
# Use -h to see options.
@@ -33,7 +33,8 @@ def initialize(command_line_args)
@changelog = nil
@user = nil
super(command_line_args)
- @description ||= @leftover && @leftover.join(" ")
+ # needs else branch coverage
+ @description ||= @leftover && @leftover.join(' ') # rubocop:disable Style/SafeNavigation
@user ||= ENV['USER']
control.env = @environment if @environment
@@ -71,17 +72,17 @@ def run
end
if !api_v1? && (@revision.nil? || @revision.empty?)
- raise "revision required when using New Relic REST API v2 with api_key. Pass in revision using: -r, --revision=REV"
+ raise 'revision required when using New Relic REST API v2 with api_key. Pass in revision using: -r, --revision=REV'
end
request = if api_v1?
- uri = "/deployments.xml"
- create_request(uri, {'x-license-key' => @license_key}, "application/octet-stream").tap do |req|
+ uri = '/deployments.xml'
+ create_request(uri, {'x-license-key' => @license_key}, 'application/octet-stream').tap do |req|
set_params_v1(req)
end
else
uri = "/v2/applications/#{application_id}/deployments.json"
- create_request(uri, {"Api-Key" => @api_key}, "application/json").tap do |req|
+ create_request(uri, {'Api-Key' => @api_key}, 'application/json').tap do |req|
set_params_v2(req)
end
end
@@ -92,7 +93,7 @@ def run
if response.is_a?(Net::HTTPSuccess)
info("Recorded deployment to '#{@appname}' (#{@description || Time.now})")
else
- err_string = REXML::Document.new(response.body).elements['errors/error'].map(&:to_s).join("; ") rescue response.message
+ err_string = REXML::Document.new(response.body).elements['errors/error'].map(&:to_s).join('; ') rescue response.message
raise NewRelic::Cli::Command::CommandFailure, "Deployment not recorded: #{err_string}"
end
rescue SystemCallError, SocketError => e
@@ -150,7 +151,7 @@ def set_params_v1(request)
def set_params_v2(request)
request.body = {
- "deployment" => {
+ 'deployment' => {
:description => @description,
:user => @user,
:revision => @revision,
@@ -161,25 +162,25 @@ def set_params_v2(request)
def options
OptionParser.new(%Q(Usage: #{$0} #{self.class.command} [OPTIONS] ["description"] ), 40) do |o|
- o.separator("OPTIONS:")
- o.on("-a", "--appname=NAME", String,
- "Set the application name.",
- "Default is app_name setting in newrelic.yml. Available only when using API v1.") { |e| @appname = e }
- o.on("-i", "--appid=ID", String,
- "Set the application ID",
- "If not provided, will connect to the New Relic collector to get it") { |i| @application_id = i }
- o.on("-e", "--environment=name", String,
- "Override the (RAILS|RUBY|RACK)_ENV setting",
+ o.separator('OPTIONS:')
+ o.on('-a', '--appname=NAME', String,
+ 'Set the application name.',
+ 'Default is app_name setting in newrelic.yml. Available only when using API v1.') { |e| @appname = e }
+ o.on('-i', '--appid=ID', String,
+ 'Set the application ID',
+ 'If not provided, will connect to the New Relic collector to get it') { |i| @application_id = i }
+ o.on('-e', '--environment=name', String,
+ 'Override the (RAILS|RUBY|RACK)_ENV setting',
"currently: #{control.env}") { |e| @environment = e }
- o.on("-u", "--user=USER", String,
- "Specify the user deploying, for information only",
+ o.on('-u', '--user=USER', String,
+ 'Specify the user deploying, for information only',
"Default: #{@user || ''}") { |u| @user = u }
- o.on("-r", "--revision=REV", String,
- "Specify the revision being deployed. Required when using New Relic REST API v2") { |r| @revision = r }
- o.on("-l", "--license-key=KEY", String,
- "Specify the license key of the account for the app being deployed") { |l| @license_key = l }
- o.on("-c", "--changes",
- "Read in a change log from the standard input") { @changelog = STDIN.read }
+ o.on('-r', '--revision=REV', String,
+ 'Specify the revision being deployed. Required when using New Relic REST API v2') { |r| @revision = r }
+ o.on('-l', '--license-key=KEY', String,
+ 'Specify the license key of the account for the app being deployed') { |l| @license_key = l }
+ o.on('-c', '--changes',
+ 'Read in a change log from the standard input') { @changelog = STDIN.read }
yield(o) if block_given?
end
end
diff --git a/lib/new_relic/cli/commands/install.rb b/lib/new_relic/cli/commands/install.rb
index 05f2432bc3..ea3a4b72c3 100644
--- a/lib/new_relic/cli/commands/install.rb
+++ b/lib/new_relic/cli/commands/install.rb
@@ -7,9 +7,9 @@
require 'erb'
class NewRelic::Cli::Install < NewRelic::Cli::Command
- NO_LICENSE_KEY = ""
+ NO_LICENSE_KEY = ''
- def self.command; "install"; end
+ def self.command; 'install'; end
# Use -h to see options.
# When command_line_args is a hash, we are invoking directly and
@@ -25,22 +25,22 @@ def initialize(command_line_args = {})
super(command_line_args)
if @dest_dir.nil?
# Install a newrelic.yml file into the local config directory.
- if File.directory?("config")
- @dest_dir = "config"
+ if File.directory?('config')
+ @dest_dir = 'config'
else
- @dest_dir = "."
+ @dest_dir = '.'
end
end
@license_key ||= NO_LICENSE_KEY
- @app_name ||= @leftover.join(" ")
+ @app_name ||= @leftover.join(' ')
@agent_version = NewRelic::VERSION::STRING
- raise CommandFailure.new("Application name required.", @options) unless @app_name && @app_name.size > 0
+ raise CommandFailure.new('Application name required.', @options) unless @app_name && @app_name.size > 0
end
def run
- dest_file = File.expand_path(@dest_dir + "/newrelic.yml")
+ dest_file = File.expand_path(@dest_dir + '/newrelic.yml')
if File.exist?(dest_file) && !@force
- raise NewRelic::Cli::Command::CommandFailure, "newrelic.yml file already exists. Use --force flag to overwrite."
+ raise NewRelic::Cli::Command::CommandFailure, 'newrelic.yml file already exists. Use --force flag to overwrite.'
end
File.open(dest_file, 'w') { |out| out.puts(content) }
@@ -63,7 +63,7 @@ def run
end
def content
- @src_file ||= File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "..", "..", "newrelic.yml"))
+ @src_file ||= File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', '..', 'newrelic.yml'))
template = File.read(@src_file)
ERB.new(template).result(binding)
end
@@ -72,10 +72,10 @@ def content
def options
OptionParser.new("Usage: #{$0} #{self.class.command} [ OPTIONS] 'application name'", 40) do |o|
- o.on("-f", "--force", "Overwrite newrelic.yml if it exists") { |e| @force = true }
- o.on("-l", "--license_key=NAME", String,
- "Use the given license key") { |e| @license_key = e }
- o.on("-d", "--destdir=name", String,
+ o.on('-f', '--force', 'Overwrite newrelic.yml if it exists') { |e| @force = true }
+ o.on('-l', '--license_key=NAME', String,
+ 'Use the given license key') { |e| @license_key = e }
+ o.on('-d', '--destdir=name', String,
"Write the newrelic.yml to the given directory, default is '.'") { |e| @dest_dir = e }
yield(o) if block_given?
end
diff --git a/lib/new_relic/collection_helper.rb b/lib/new_relic/collection_helper.rb
index 9005c36506..5ba0992f2d 100644
--- a/lib/new_relic/collection_helper.rb
+++ b/lib/new_relic/collection_helper.rb
@@ -40,7 +40,7 @@ def flatten(object)
when nil then ''
when object.instance_of?(String) then object
when String then String.new(object) # convert string subclasses to strings
- else String.new("#<#{object.class}>")
+ else +"#<#{object.class}>"
end
end
@@ -52,7 +52,7 @@ def truncate(string, len = DEFAULT_TRUNCATION_SIZE)
real_string = flatten(string)
if real_string.size > len
real_string = real_string.slice(0...len)
- real_string << "..."
+ real_string << '...'
end
real_string
else
diff --git a/lib/new_relic/constants.rb b/lib/new_relic/constants.rb
index 58a5c5280b..847b73a994 100644
--- a/lib/new_relic/constants.rb
+++ b/lib/new_relic/constants.rb
@@ -7,16 +7,16 @@ module NewRelic
EMPTY_ARRAY = [].freeze
EMPTY_HASH = {}.freeze
- EMPTY_STR = ""
+ EMPTY_STR = ''
- HTTP = "HTTP"
- HTTPS = "HTTPS"
- UNKNOWN = "Unknown"
+ HTTP = 'HTTP'
+ HTTPS = 'HTTPS'
+ UNKNOWN = 'Unknown'
FORMAT_NON_RACK = 0
FORMAT_RACK = 1
- NEWRELIC_KEY = "newrelic"
+ NEWRELIC_KEY = 'newrelic'
CANDIDATE_NEWRELIC_KEYS = [
NEWRELIC_KEY,
'NEWRELIC',
@@ -24,8 +24,8 @@ module NewRelic
'Newrelic'
].freeze
- TRACEPARENT_KEY = "traceparent"
- TRACESTATE_KEY = "tracestate"
+ TRACEPARENT_KEY = 'traceparent'
+ TRACESTATE_KEY = 'tracestate'
STANDARD_OUT = 'STDOUT'
@@ -34,6 +34,5 @@ module NewRelic
HTTP_NEWRELIC_KEY = "HTTP_#{NEWRELIC_KEY.upcase}"
CONNECT_RETRY_PERIODS = [15, 15, 30, 60, 120, 300]
- MIN_RETRY_PERIOD = 15
MAX_RETRY_PERIOD = 300
end
diff --git a/lib/new_relic/control/class_methods.rb b/lib/new_relic/control/class_methods.rb
index 8e3b1f4717..bdd900fa70 100644
--- a/lib/new_relic/control/class_methods.rb
+++ b/lib/new_relic/control/class_methods.rb
@@ -35,8 +35,8 @@ def new_instance
# nb this does not 'load test' the framework, it loads the 'test framework'
def load_test_framework
- config = File.expand_path(File.join('..', '..', '..', '..', "test", "config", "newrelic.yml"), __FILE__)
- require "config/test_control"
+ config = File.expand_path(File.join('..', '..', '..', '..', 'test', 'config', 'newrelic.yml'), __FILE__)
+ require 'config/test_control'
NewRelic::Control::Frameworks::Test.new(local_env, config)
end
@@ -54,7 +54,7 @@ def load_framework_class(framework)
# The root directory for the plugin or gem
def newrelic_root
- File.expand_path(File.join("..", "..", "..", ".."), __FILE__)
+ File.expand_path(File.join('..', '..', '..', '..'), __FILE__)
end
def camelize(snake_case_name)
diff --git a/lib/new_relic/control/frameworks/rails.rb b/lib/new_relic/control/frameworks/rails.rb
index 9705f7a46c..e53d326897 100644
--- a/lib/new_relic/control/frameworks/rails.rb
+++ b/lib/new_relic/control/frameworks/rails.rb
@@ -44,26 +44,38 @@ def rails_config
# find a config and use that.
def init_config(options = {})
@config = options[:config]
- # Install the dependency detection,
- if rails_config && ::Rails.configuration.respond_to?(:after_initialize)
- rails_config.after_initialize do
- # This will insure we load all the instrumentation as late as possible. If the agent
- # is not enabled, it will load a limited amount of instrumentation.
- DependencyDetection.detect!
- end
+ install_dependency_detection
+ install_browser_monitoring_and_agent_hooks
+ rescue => e
+ ::NewRelic::Agent.logger.error('Failure during init_config for Rails. Is Rails required in a non-Rails ' \
+ 'app? Set NEW_RELIC_FRAMEWORK=ruby to avoid this message. The Ruby agent ' \
+ 'will continue running, but Rails-specific features may be missing. ' \
+ "#{e.class} - #{e.message}")
+ end
+
+ def install_dependency_detection
+ return unless rails_config && ::Rails.configuration.respond_to?(:after_initialize)
+
+ rails_config.after_initialize do
+ # This will insure we load all the instrumentation as late as
+ # possible. If the agent is not enabled, it will load a limited
+ # amount of instrumentation.
+ DependencyDetection.detect!
end
+ end
+
+ def install_browser_monitoring_and_agent_hooks
+ return unless rails_config
+
if !Agent.config[:agent_enabled]
- # Might not be running if it does not think mongrel, thin, passenger, etc
- # is running, if it thinks it's a rake task, or if the agent_enabled is false.
- ::NewRelic::Agent.logger.info("New Relic Agent not running.")
+ # Might not be running if it does not think mongrel, thin,
+ # passenger, etc. is running, if it thinks it's a rake task, or
+ # if the agent_enabled is false.
+ ::NewRelic::Agent.logger.info('New Relic Agent not running. Skipping browser monitoring and agent hooks.')
else
install_browser_monitoring(rails_config)
install_agent_hooks(rails_config)
end
- rescue => e
- ::NewRelic::Agent.logger.error("Failure during init_config for Rails. Is Rails required in a non-Rails app? Set NEW_RELIC_FRAMEWORK=ruby to avoid this message.",
- "The Ruby agent will continue running, but Rails-specific features may be missing.",
- e)
end
def install_agent_hooks(config)
@@ -77,9 +89,9 @@ def install_agent_hooks(config)
return unless NewRelic::Rack::AgentHooks.needed?
config.middleware.use(NewRelic::Rack::AgentHooks)
- ::NewRelic::Agent.logger.debug("Installed New Relic Agent Hooks middleware")
+ ::NewRelic::Agent.logger.debug('Installed New Relic Agent Hooks middleware')
rescue => e
- ::NewRelic::Agent.logger.warn("Error installing New Relic Agent Hooks middleware", e)
+ ::NewRelic::Agent.logger.warn('Error installing New Relic Agent Hooks middleware', e)
end
end
@@ -93,9 +105,9 @@ def install_browser_monitoring(config)
begin
require 'new_relic/rack/browser_monitoring'
config.middleware.use(NewRelic::Rack::BrowserMonitoring)
- ::NewRelic::Agent.logger.debug("Installed New Relic Browser Monitoring middleware")
+ ::NewRelic::Agent.logger.debug('Installed New Relic Browser Monitoring middleware')
rescue => e
- ::NewRelic::Agent.logger.warn("Error installing New Relic Browser Monitoring middleware", e)
+ ::NewRelic::Agent.logger.warn('Error installing New Relic Browser Monitoring middleware', e)
end
end
end
diff --git a/lib/new_relic/control/instance_methods.rb b/lib/new_relic/control/instance_methods.rb
index 1fe5738984..44e8f1dd47 100644
--- a/lib/new_relic/control/instance_methods.rb
+++ b/lib/new_relic/control/instance_methods.rb
@@ -82,10 +82,10 @@ def determine_env(options)
if @started_in_env && @started_in_env != env
Agent.logger.error("Attempted to start agent in #{env.inspect} environment, but agent was already running " \
"in #{@started_in_env.inspect}", "The agent will continue running in #{@started_in_env.inspect}. To " \
- "alter this, ensure the desired environment is set before the agent starts.")
+ 'alter this, ensure the desired environment is set before the agent starts.')
else
Agent.logger.info("Starting the New Relic agent version #{NewRelic::VERSION::STRING} in #{env.inspect} " \
- "environment.", "To prevent agent startup add a NEW_RELIC_AGENT_ENABLED=false environment variable or " \
+ 'environment.', 'To prevent agent startup add a NEW_RELIC_AGENT_ENABLED=false environment variable or ' \
"modify the #{env.inspect} section of your newrelic.yml.")
end
@@ -106,9 +106,9 @@ def security_settings_valid?
end
def handle_invalid_security_settings
- NewRelic::Agent.logger.error("Security Policies and High Security Mode cannot both be present in the agent " \
- "configuration. If Security Policies have been set for your account, please ensure the " \
- "security_policies_token is set but high_security is disabled (default).")
+ NewRelic::Agent.logger.error('Security Policies and High Security Mode cannot both be present in the agent ' \
+ 'configuration. If Security Policies have been set for your account, please ensure the ' \
+ 'security_policies_token is set but high_security is disabled (default).')
install_shim
end
diff --git a/lib/new_relic/control/instrumentation.rb b/lib/new_relic/control/instrumentation.rb
index db502b3430..00cb66d2d2 100644
--- a/lib/new_relic/control/instrumentation.rb
+++ b/lib/new_relic/control/instrumentation.rb
@@ -64,7 +64,7 @@ def _install_instrumentation
DependencyDetection.detect!
ruby_deprecation
rails_32_deprecation
- ::NewRelic::Agent.logger.info("Finished instrumentation")
+ ::NewRelic::Agent.logger.info('Finished instrumentation')
end
end
diff --git a/lib/new_relic/control/private_instance_methods.rb b/lib/new_relic/control/private_instance_methods.rb
index 2640f491e6..bcd14c7a81 100644
--- a/lib/new_relic/control/private_instance_methods.rb
+++ b/lib/new_relic/control/private_instance_methods.rb
@@ -12,7 +12,7 @@ module PrivateInstanceMethods
def configure_high_security
if security_settings_valid? && Agent.config[:high_security]
- Agent.logger.info("Installing high security configuration based on local configuration")
+ Agent.logger.info('Installing high security configuration based on local configuration')
Agent.config.replace_or_add_config(Agent::Configuration::HighSecuritySource.new(Agent.config))
end
end
diff --git a/lib/new_relic/dependency_detection.rb b/lib/new_relic/dependency_detection.rb
index bc90651ebc..49a7ce2c41 100644
--- a/lib/new_relic/dependency_detection.rb
+++ b/lib/new_relic/dependency_detection.rb
@@ -35,19 +35,6 @@ def dependency_by_name(name)
@items.find { |i| i.name == name }
end
- def installed?(name)
- item = dependency_by_name(name)
- item && item.executed
- end
-
- def items
- @items
- end
-
- def items=(new_items)
- @items = new_items
- end
-
class Dependent
attr_reader :executed
attr_accessor :name
@@ -83,7 +70,7 @@ def source_location_for(klass, method_name)
# Given "NewRelic::Agent::Instrumentation::NetHTTP::Prepend"
# Will extract "NetHTTP" which is in the 2nd to last spot
def extract_supportability_name(instrumenting_module)
- instrumenting_module.to_s.split("::")[-2]
+ instrumenting_module.to_s.split('::')[-2]
end
def log_and_instrument(method, instrumenting_module, supportability_name)
@@ -94,20 +81,20 @@ def log_and_instrument(method, instrumenting_module, supportability_name)
end
def prepend_instrument(target_class, instrumenting_module, supportability_name = nil)
- log_and_instrument("Prepend", instrumenting_module, supportability_name) do
+ log_and_instrument('Prepend', instrumenting_module, supportability_name) do
target_class.send(:prepend, instrumenting_module)
end
end
def chain_instrument(instrumenting_module, supportability_name = nil)
- log_and_instrument("MethodChaining", instrumenting_module, supportability_name) do
+ log_and_instrument('MethodChaining', instrumenting_module, supportability_name) do
instrumenting_module.instrument!
end
end
def chain_instrument_target(target, instrumenting_module, supportability_name = nil)
NewRelic::Agent.logger.info("Installing deferred #{target} instrumentation")
- log_and_instrument("MethodChaining", instrumenting_module, supportability_name) do
+ log_and_instrument('MethodChaining', instrumenting_module, supportability_name) do
instrumenting_module.instrument!(target)
end
end
diff --git a/lib/new_relic/environment_report.rb b/lib/new_relic/environment_report.rb
index 37026c1620..b9ea4b330b 100644
--- a/lib/new_relic/environment_report.rb
+++ b/lib/new_relic/environment_report.rb
@@ -52,7 +52,7 @@ def self.registered_reporters=(logic)
# though so try it if the above fails.
Bundler.load.specs.map do |spec|
version = (spec.respond_to?(:version) && spec.version)
- spec.name + (version ? "(#{version})" : "")
+ spec.name + (version ? "(#{version})" : '')
end
end
end
@@ -118,19 +118,19 @@ def to_a
def record_value(data, key, value)
data[key] = value
- Agent.record_metric("Supportability/EnvironmentReport/success", 0.0)
+ Agent.record_metric('Supportability/EnvironmentReport/success', 0.0)
Agent.record_metric("Supportability/EnvironmentReport/success/#{key}", 0.0)
end
def record_empty_value(key, value)
Agent.logger.debug("EnvironmentReport ignoring value for #{key.inspect} which came back falsey: #{value.inspect}")
- Agent.record_metric("Supportability/EnvironmentReport/empty", 0.0)
+ Agent.record_metric('Supportability/EnvironmentReport/empty', 0.0)
Agent.record_metric("Supportability/EnvironmentReport/empty/#{key}", 0.0)
end
def rescue_initialize(key, exception)
Agent.logger.debug("EnvironmentReport failed to retrieve value for #{key.inspect}: #{exception}")
- Agent.record_metric("Supportability/EnvironmentReport/error", 0.0)
+ Agent.record_metric('Supportability/EnvironmentReport/error', 0.0)
Agent.record_metric("Supportability/EnvironmentReport/error/#{key}", 0.0)
end
end
diff --git a/lib/new_relic/helper.rb b/lib/new_relic/helper.rb
index 0cd415030a..7d17c89908 100644
--- a/lib/new_relic/helper.rb
+++ b/lib/new_relic/helper.rb
@@ -63,7 +63,8 @@ def run_command(command)
raise NewRelic::CommandRunFailedError.new("Failed to run command '#{command}': #{message}")
end
- output.chomp if output
+ # needs else branch coverage
+ output.chomp if output # rubocop:disable Style/SafeNavigation
end
# TODO: Open3 defers the actual execution of a binary to Process.spawn,
diff --git a/lib/new_relic/language_support.rb b/lib/new_relic/language_support.rb
index 5014c27764..e95fe1c391 100644
--- a/lib/new_relic/language_support.rb
+++ b/lib/new_relic/language_support.rb
@@ -62,7 +62,7 @@ def constantize(const_name)
#
# Can't help if the constant isn't a class...
if result.is_a?(Module)
- expected_name = "#{namespace}::#{name}".gsub(/^Object::/, "")
+ expected_name = "#{namespace}::#{name}".gsub(/^Object::/, '')
return unless expected_name == result.to_s
end
diff --git a/lib/new_relic/latest_changes.rb b/lib/new_relic/latest_changes.rb
index 6d2ce135e3..68c194bb1a 100644
--- a/lib/new_relic/latest_changes.rb
+++ b/lib/new_relic/latest_changes.rb
@@ -26,12 +26,12 @@ def self.read(changelog = default_changelog)
# * This is a patch item (3.7.1.188)
def self.read_patch(patch_level, changelog = default_changelog)
latest = extract_latest_changes(File.read(changelog))
- changes = ["## v#{patch_level}", ""]
+ changes = ["## v#{patch_level}", '']
current_item = nil
latest.each do |line|
- if line =~ /^\s*\*.*/
- if line =~ /\(#{patch_level}\)/
+ if /^\s*\*.*/.match?(line)
+ if /\(#{patch_level}\)/.match?(line)
# Found a patch level item, so start tracking the lines!
current_item = line
else
@@ -52,12 +52,12 @@ def self.extract_latest_changes(contents)
changes = []
version_count = 0
contents.each_line do |line|
- if line =~ /##\s+v[\d.]+/
+ if /##\s+v[\d.]+/.match?(line)
version_count += 1
end
break if version_count >= 2
- changes << line.sub(/^ \* /, "* ").chomp
+ changes << line.sub(/^ \* /, '* ').chomp
end
changes
end
diff --git a/lib/new_relic/noticed_error.rb b/lib/new_relic/noticed_error.rb
index 8a949066a6..121c8e43ad 100644
--- a/lib/new_relic/noticed_error.rb
+++ b/lib/new_relic/noticed_error.rb
@@ -15,18 +15,20 @@ class NewRelic::NoticedError
:stack_trace, :attributes_from_notice_error, :attributes,
:expected
- attr_reader :exception_id, :is_internal
+ attr_reader :error_group, :exception_id, :is_internal
STRIPPED_EXCEPTION_REPLACEMENT_MESSAGE = "Message removed by New Relic 'strip_exception_messages' setting"
UNKNOWN_ERROR_CLASS_NAME = 'Error'
NIL_ERROR_MESSAGE = ''
- USER_ATTRIBUTES = "userAttributes"
- AGENT_ATTRIBUTES = "agentAttributes"
- INTRINSIC_ATTRIBUTES = "intrinsics"
+ USER_ATTRIBUTES = 'userAttributes'
+ AGENT_ATTRIBUTES = 'agentAttributes'
+ INTRINSIC_ATTRIBUTES = 'intrinsics'
DESTINATION = NewRelic::Agent::AttributeFilter::DST_ERROR_COLLECTOR
+ AGENT_ATTRIBUTE_ERROR_GROUP = :'error.group.name'
+
ERROR_PREFIX_KEY = 'error'
ERROR_MESSAGE_KEY = "#{ERROR_PREFIX_KEY}.message"
ERROR_CLASS_KEY = "#{ERROR_PREFIX_KEY}.class"
@@ -141,21 +143,9 @@ def build_error_attributes
end
def build_agent_attributes(merged_attributes)
- agent_attributes = if @attributes
- @attributes.agent_attributes_for(DESTINATION)
- else
- NewRelic::EMPTY_HASH
- end
-
- # It's possible to override the request_uri from the transaction attributes
- # with a uri passed to notice_error. Add it to merged_attributes filter and
- # merge with the transaction attributes, possibly overriding the request_uri
- if request_uri
- merged_attributes.add_agent_attribute(:'request.uri', request_uri, DESTINATION)
- agent_attributes.merge(merged_attributes.agent_attributes_for(DESTINATION))
- end
+ return NewRelic::EMPTY_HASH unless @attributes
- agent_attributes
+ @attributes.agent_attributes_for(DESTINATION)
end
def build_intrinsic_attributes
@@ -197,4 +187,16 @@ def extract_class_name_and_message_from(exception)
@message = exception.to_s
end
end
+
+ def error_group=(name)
+ return if name.nil? || name.empty?
+
+ if agent_attributes.frozen?
+ processed_attributes[AGENT_ATTRIBUTES] = agent_attributes.merge(AGENT_ATTRIBUTE_ERROR_GROUP => name)
+ else
+ agent_attributes[AGENT_ATTRIBUTE_ERROR_GROUP] = name
+ end
+
+ @error_group = name
+ end
end
diff --git a/lib/new_relic/rack/browser_monitoring.rb b/lib/new_relic/rack/browser_monitoring.rb
index e366f2be0b..83cd7c2718 100644
--- a/lib/new_relic/rack/browser_monitoring.rb
+++ b/lib/new_relic/rack/browser_monitoring.rb
@@ -26,11 +26,11 @@ class BrowserMonitoring < AgentMiddleware
ATTACHMENT = 'attachment'.freeze
TEXT_HTML = 'text/html'.freeze
- BODY_START = "]+charset\s*=[^>]*>/im.freeze
X_UA_COMPATIBLE_RE = /<\s*meta[^>]+http-equiv\s*=\s*['"]x-ua-compatible['"][^>]*>/im.freeze
@@ -40,7 +40,7 @@ def traced_call(env)
js_to_inject = NewRelic::Agent.browser_timing_header
if (js_to_inject != NewRelic::EMPTY_STR) && should_instrument?(env, status, headers)
- response_string = autoinstrument_source(response, headers, js_to_inject)
+ response_string = autoinstrument_source(response, js_to_inject)
if headers.key?(CONTENT_LENGTH)
content_length = response_string ? response_string.bytesize : 0
headers[CONTENT_LENGTH] = content_length.to_s
@@ -69,11 +69,17 @@ def should_instrument?(env, status, headers)
private
- def autoinstrument_source(response, headers, js_to_inject)
+ def autoinstrument_source(response, js_to_inject)
source = gather_source(response)
close_old_response(response)
- return nil unless source
+ return unless source
+ modify_source(source, js_to_inject)
+ rescue => e
+ NewRelic::Agent.logger.debug("Skipping RUM instrumentation on exception: #{e.class} - #{e.message}")
+ end
+
+ def modify_source(source, js_to_inject)
# Only scan the first 50k (roughly) then give up.
beginning_of_source = source[0..SCAN_LIMIT]
meta_tag_positions = find_meta_tag_positions(beginning_of_source)
@@ -81,26 +87,24 @@ def autoinstrument_source(response, headers, js_to_inject)
if insertion_index = find_insertion_index(meta_tag_positions, beginning_of_source, body_start)
source = source_injection(source, insertion_index, js_to_inject)
else
- NewRelic::Agent.logger.debug("Skipping RUM instrumentation. Could not properly determine location to inject script.")
+ NewRelic::Agent.logger.debug('Skipping RUM instrumentation. Could not properly determine location to ' \
+ 'inject script.')
end
else
msg = "Skipping RUM instrumentation. Unable to find tag in first #{SCAN_LIMIT} bytes of document."
NewRelic::Agent.logger.log_once(:warn, :rum_insertion_failure, msg)
NewRelic::Agent.logger.debug(msg)
end
-
source
- rescue => e
- NewRelic::Agent.logger.debug("Skipping RUM instrumentation on exception.", e)
- nil
end
def html?(headers)
- headers[CONTENT_TYPE] && headers[CONTENT_TYPE].include?(TEXT_HTML)
+ # needs else branch coverage
+ headers[CONTENT_TYPE] && headers[CONTENT_TYPE].include?(TEXT_HTML) # rubocop:disable Style/SafeNavigation
end
def attachment?(headers)
- headers[CONTENT_DISPOSITION] && headers[CONTENT_DISPOSITION].include?(ATTACHMENT)
+ headers[CONTENT_DISPOSITION]&.include?(ATTACHMENT)
end
def streaming?(env, headers)
@@ -150,12 +154,12 @@ def find_body_start(beginning_of_source)
def find_x_ua_compatible_position(beginning_of_source)
match = X_UA_COMPATIBLE_RE.match(beginning_of_source)
- match.end(0) if match
+ match&.end(0)
end
def find_charset_position(beginning_of_source)
match = CHARSET_RE.match(beginning_of_source)
- match.end(0) if match
+ match&.end(0)
end
def find_end_of_head_open(beginning_of_source)
diff --git a/lib/new_relic/recipes/capistrano3.rb b/lib/new_relic/recipes/capistrano3.rb
index acbe4d81ca..f841a00702 100644
--- a/lib/new_relic/recipes/capistrano3.rb
+++ b/lib/new_relic/recipes/capistrano3.rb
@@ -8,7 +8,7 @@
namespace :newrelic do
include SendDeployment
# notifies New Relic of a deployment
- desc "Record a deployment in New Relic (newrelic.com)"
+ desc 'Record a deployment in New Relic (newrelic.com)'
task :notice_deployment do
if fetch(:newrelic_role)
on roles(fetch(:newrelic_role)) do
diff --git a/lib/new_relic/recipes/capistrano_legacy.rb b/lib/new_relic/recipes/capistrano_legacy.rb
index 8f72367b4c..6d329eb765 100644
--- a/lib/new_relic/recipes/capistrano_legacy.rb
+++ b/lib/new_relic/recipes/capistrano_legacy.rb
@@ -5,9 +5,9 @@
make_notify_task = proc do
namespace(:newrelic) do
# on all deployments, notify New Relic
- desc("Record a deployment in New Relic (newrelic.com)")
+ desc('Record a deployment in New Relic (newrelic.com)')
task(:notice_deployment, :roles => :app, :except => {:no_release => true}) do
- rails_env = fetch(:newrelic_rails_env, fetch(:rails_env, "production"))
+ rails_env = fetch(:newrelic_rails_env, fetch(:rails_env, 'production'))
require 'new_relic/cli/command'
@@ -36,14 +36,14 @@
:license_key => license_key
}
- logger.debug("Uploading deployment to New Relic")
+ logger.debug('Uploading deployment to New Relic')
deployment = NewRelic::Cli::Deployments.new(deploy_options)
deployment.run
- logger.info("Uploaded deployment information to New Relic")
+ logger.info('Uploaded deployment information to New Relic')
rescue NewRelic::Cli::Command::CommandFailure => e
logger.info(e.message)
rescue Capistrano::CommandError
- logger.info("Unable to notify New Relic of the deployment... skipping")
+ logger.info('Unable to notify New Relic of the deployment... skipping')
rescue => e
logger.info("Error creating New Relic deployment (#{e})\n#{e.backtrace.join("\n")}")
end
@@ -51,7 +51,7 @@
def lookup_changelog(changelog)
if !changelog
- logger.debug("Getting log of changes for New Relic Deployment details")
+ logger.debug('Getting log of changes for New Relic Deployment details')
from_revision = source.next_revision(current_revision)
if scm == :git
diff --git a/lib/new_relic/recipes/helpers/send_deployment.rb b/lib/new_relic/recipes/helpers/send_deployment.rb
index f3d83f64d3..7304fd4a82 100644
--- a/lib/new_relic/recipes/helpers/send_deployment.rb
+++ b/lib/new_relic/recipes/helpers/send_deployment.rb
@@ -5,9 +5,9 @@
module SendDeployment
def send_deployment_notification_to_newrelic
require 'new_relic/cli/command'
- debug("Uploading deployment to New Relic")
+ debug('Uploading deployment to New Relic')
NewRelic::Cli::Deployments.new(deploy_options).run
- info("Uploaded deployment information to New Relic")
+ info('Uploaded deployment information to New Relic')
rescue NewRelic::Cli::Command::CommandFailure => e
info(e.message)
rescue => e
@@ -34,7 +34,7 @@ def fetch_changelog
end
def fetch_environment
- fetch(:newrelic_rails_env, fetch(:rack_env, fetch(:rails_env, fetch(:stage, "production"))))
+ fetch(:newrelic_rails_env, fetch(:rack_env, fetch(:rails_env, fetch(:stage, 'production'))))
end
def fetch_rev
@@ -59,9 +59,9 @@ def lookup_changelog
current_revision = fetch(:current_revision)
return unless current_revision && previous_revision
- debug("Retrieving changelog for New Relic Deployment details")
+ debug('Retrieving changelog for New Relic Deployment details')
- if Rake::Task.task_defined?("git:check")
+ if Rake::Task.task_defined?('git:check')
log_command = "git --no-pager log --no-color --pretty=format:' * %an: %s' " +
"--abbrev-commit --no-merges #{previous_revision}..#{current_revision}"
`#{log_command}`
diff --git a/lib/new_relic/supportability_helper.rb b/lib/new_relic/supportability_helper.rb
index abee118dac..d7b43eb200 100644
--- a/lib/new_relic/supportability_helper.rb
+++ b/lib/new_relic/supportability_helper.rb
@@ -44,8 +44,10 @@ module SupportabilityHelper
:record_metric,
:recording_web_transaction?,
:require_test_helper,
+ :set_error_group_callback,
:set_sql_obfuscator,
:set_transaction_name,
+ :set_user_id,
:shutdown,
:start_segment,
:trace,
diff --git a/lib/new_relic/version.rb b/lib/new_relic/version.rb
index 1bd701fd79..854f9f02b5 100644
--- a/lib/new_relic/version.rb
+++ b/lib/new_relic/version.rb
@@ -6,7 +6,7 @@
module NewRelic
module VERSION # :nodoc:
MAJOR = 9
- MINOR = 0
+ MINOR = 1
TINY = 0
STRING = "#{MAJOR}.#{MINOR}.#{TINY}"
diff --git a/lib/newrelic_rpm.rb b/lib/newrelic_rpm.rb
index 67c472cd9a..3d70f829d3 100644
--- a/lib/newrelic_rpm.rb
+++ b/lib/newrelic_rpm.rb
@@ -21,16 +21,16 @@
module NewRelic
class Railtie < Rails::Railtie
if ENV['NEW_RELIC_DEFER_RAILS_INITIALIZATION']
- initializer "newrelic_rpm.include_method_tracers", before: :load_config_initializers do |app|
+ initializer 'newrelic_rpm.include_method_tracers', before: :load_config_initializers do |app|
Module.send(:include, NewRelic::Agent::MethodTracer::ClassMethods)
Module.send(:include, NewRelic::Agent::MethodTracer)
end
- initializer "newrelic_rpm.start_plugin", after: :load_config_initializers do |app|
+ initializer 'newrelic_rpm.start_plugin', after: :load_config_initializers do |app|
NewRelic::Control.instance.init_plugin(config: app.config)
end
else
- initializer "newrelic_rpm.start_plugin", before: :load_config_initializers do |app|
+ initializer 'newrelic_rpm.start_plugin', before: :load_config_initializers do |app|
NewRelic::Control.instance.init_plugin(config: app.config)
end
end
diff --git a/lib/sequel/extensions/new_relic_instrumentation.rb b/lib/sequel/extensions/new_relic_instrumentation.rb
index 02d3c0dcda..a235f68c3c 100644
--- a/lib/sequel/extensions/new_relic_instrumentation.rb
+++ b/lib/sequel/extensions/new_relic_instrumentation.rb
@@ -32,7 +32,7 @@ module Sequel
module NewRelicInstrumentation
module Naming
def self.query_method_name
- if Sequel::VERSION >= "4.35.0"
+ if Sequel::VERSION >= '4.35.0'
:log_connection_yield
else
:log_yield
@@ -86,13 +86,13 @@ def explainer_for(sql)
if THREAD_SAFE_CONNECTION_POOL_CLASSES.include?(self.pool.class)
self[sql].explain
else
- NewRelic::Agent.logger.log_once(:info, :sequel_explain_skipped, "Not running SQL explains because Sequel is not in recognized multi-threaded mode")
+ NewRelic::Agent.logger.log_once(:info, :sequel_explain_skipped, 'Not running SQL explains because Sequel is not in recognized multi-threaded mode')
nil
end
end
end
end # module NewRelicInstrumentation
- NewRelic::Agent.logger.debug("Registering the :new_relic_instrumentation extension.")
+ NewRelic::Agent.logger.debug('Registering the :new_relic_instrumentation extension.')
Database.register_extension(:new_relic_instrumentation, NewRelicInstrumentation)
end # module Sequel
diff --git a/lib/sequel/plugins/new_relic_instrumentation.rb b/lib/sequel/plugins/new_relic_instrumentation.rb
index 8271e0d24b..106dd9af09 100644
--- a/lib/sequel/plugins/new_relic_instrumentation.rb
+++ b/lib/sequel/plugins/new_relic_instrumentation.rb
@@ -54,7 +54,7 @@ module InstanceMethods
module ClassMethods
extend Sequel::Plugins::NewRelicInstrumentation::MethodWrapping
- wrap_sequel_method :[], "get"
+ wrap_sequel_method :[], 'get'
wrap_sequel_method :all
wrap_sequel_method :first
wrap_sequel_method :create
diff --git a/lib/tasks/config.rake b/lib/tasks/config.rake
index 4d82d2670e..9775fb9a7b 100644
--- a/lib/tasks/config.rake
+++ b/lib/tasks/config.rake
@@ -7,9 +7,9 @@ include Format
namespace :newrelic do
namespace :config do
- GENERAL = "general"
- DISABLING = "disabling"
- ATTRIBUTES = "attributes"
+ GENERAL = 'general'
+ DISABLING = 'disabling'
+ ATTRIBUTES = 'attributes'
# these configuration options are not able to be set using environment variables
NON_ENV_CONFIGS = ['error_collector.ignore_classes', 'error_collector.ignore_messages', 'error_collector.expected_classes', 'error_collector.expected_messages']
@@ -18,21 +18,21 @@ namespace :newrelic do
GENERAL => 'These settings are available for agent configuration. Some settings depend on your New Relic subscription level.',
DISABLING => 'Use these settings to toggle instrumentation types during agent startup.',
ATTRIBUTES => '[Attributes](/docs/features/agent-attributes) are key-value pairs containing information that determines the properties of an event or transaction. These key-value pairs can be viewed within transaction traces in APM, traced errors in APM, transaction events in dashboards, and page views in dashboards. You can customize exactly which attributes will be sent to each of these destinations',
- "transaction_tracer" => 'The [transaction traces](/docs/apm/traces/transaction-traces/transaction-traces) feature collects detailed information from a selection of transactions, including a summary of the calling sequence, a breakdown of time spent, and a list of SQL queries and their query plans (on mysql and postgresql). Available features depend on your New Relic subscription level.',
- "error_collector" => "The agent collects and reports all uncaught exceptions by default. These configuration options allow you to customize the error collection.\n\nFor information on ignored and expected errors, [see this page on Error Analytics in APM](/docs/agents/manage-apm-agents/agent-data/manage-errors-apm-collect-ignore-or-mark-expected/). To set expected errors via the `NewRelic::Agent.notice_error` Ruby method, [consult the Ruby Agent API](/docs/agents/ruby-agent/api-guides/sending-handled-errors-new-relic/).",
- "browser_monitoring" => "The browser monitoring [page load timing](/docs/browser/new-relic-browser/page-load-timing/page-load-timing-process) feature (sometimes referred to as real user monitoring or RUM) gives you insight into the performance real users are experiencing with your website. This is accomplished by measuring the time it takes for your users' browsers to download and render your web pages by injecting a small amount of JavaScript code into the header and footer of each page.",
- "analytics_events" => '[New Relic dashboards](/docs/query-your-data/explore-query-data/dashboards/introduction-new-relic-one-dashboards) is a resource to gather and visualize data about your software and what it says about your business. With it you can quickly and easily create real-time dashboards to get immediate answers about end-user experiences, clickstreams, mobile activities, and server transactions.'
+ 'transaction_tracer' => 'The [transaction traces](/docs/apm/traces/transaction-traces/transaction-traces) feature collects detailed information from a selection of transactions, including a summary of the calling sequence, a breakdown of time spent, and a list of SQL queries and their query plans (on mysql and postgresql). Available features depend on your New Relic subscription level.',
+ 'error_collector' => "The agent collects and reports all uncaught exceptions by default. These configuration options allow you to customize the error collection.\n\nFor information on ignored and expected errors, [see this page on Error Analytics in APM](/docs/agents/manage-apm-agents/agent-data/manage-errors-apm-collect-ignore-or-mark-expected/). To set expected errors via the `NewRelic::Agent.notice_error` Ruby method, [consult the Ruby Agent API](/docs/agents/ruby-agent/api-guides/sending-handled-errors-new-relic/).",
+ 'browser_monitoring' => "The browser monitoring [page load timing](/docs/browser/new-relic-browser/page-load-timing/page-load-timing-process) feature (sometimes referred to as real user monitoring or RUM) gives you insight into the performance real users are experiencing with your website. This is accomplished by measuring the time it takes for your users' browsers to download and render your web pages by injecting a small amount of JavaScript code into the header and footer of each page.",
+ 'analytics_events' => '[New Relic dashboards](/docs/query-your-data/explore-query-data/dashboards/introduction-new-relic-one-dashboards) is a resource to gather and visualize data about your software and what it says about your business. With it you can quickly and easily create real-time dashboards to get immediate answers about end-user experiences, clickstreams, mobile activities, and server transactions.'
}
NAME_OVERRIDES = {
- "slow_sql" => "Slow SQL",
- "custom_insights_events" => "Custom Events"
+ 'slow_sql' => 'Slow SQL',
+ 'custom_insights_events' => 'Custom Events'
}
- desc "Describe available New Relic configuration settings"
+ desc 'Describe available New Relic configuration settings'
task :docs, [:format] => [] do |t, args|
- require File.expand_path(File.join(File.dirname(__FILE__), "..", "new_relic", "agent", "configuration", "default_source.rb"))
- format = args[:format] || "text"
+ require File.expand_path(File.join(File.dirname(__FILE__), '..', 'new_relic', 'agent', 'configuration', 'default_source.rb'))
+ format = args[:format] || 'text'
output(format)
end
end
diff --git a/lib/tasks/coverage_report.rake b/lib/tasks/coverage_report.rake
index c87ea1652f..0a632fc36b 100644
--- a/lib/tasks/coverage_report.rake
+++ b/lib/tasks/coverage_report.rake
@@ -4,7 +4,7 @@
if ENV['CI']
namespace :coverage do
- desc "Collates all result sets generated by the different test runners"
+ desc 'Collates all result sets generated by the different test runners'
task :report do
require 'simplecov'
require 'fileutils'
@@ -19,10 +19,10 @@ if ENV['CI']
Dir['lib/coverage_{[!r][!e][!s][!u][!l][!t][!s]}*'].each { |dir| FileUtils.rm_rf(dir) }
end
- desc "Removes all coverage_* directories"
+ desc 'Removes all coverage_* directories'
task :clear do
require 'fileutils'
- Dir["lib/coverage_*"].each { |dir| FileUtils.rm_rf(dir) }
+ Dir['lib/coverage_*'].each { |dir| FileUtils.rm_rf(dir) }
end
end
end
diff --git a/lib/tasks/helpers/format.rb b/lib/tasks/helpers/format.rb
index 033adf91d2..4a0890ed35 100644
--- a/lib/tasks/helpers/format.rb
+++ b/lib/tasks/helpers/format.rb
@@ -66,24 +66,24 @@ def format_default_value(spec)
def format_description(value)
description = ''
- description += "DEPRECATED " if value[:deprecated]
+ description += 'DEPRECATED ' if value[:deprecated]
description += value[:description]
description
end
def format_env_var(key)
- return "None" if NON_ENV_CONFIGS.include?(key)
+ return 'None' if NON_ENV_CONFIGS.include?(key)
- "NEW_RELIC_#{key.tr(".", "_").upcase}"
+ "NEW_RELIC_#{key.tr('.', '_').upcase}"
end
def format_name(key)
name = NAME_OVERRIDES[key]
return name if name
- key.split("_")
+ key.split('_')
.each { |fragment| fragment[0] = fragment[0].upcase }
- .join(" ")
+ .join(' ')
end
def format_sections(key, value)
@@ -98,7 +98,7 @@ def format_sections(key, value)
def format_type(type)
if type == NewRelic::Agent::Configuration::Boolean
- "Boolean"
+ 'Boolean'
else
type
end
@@ -110,11 +110,11 @@ def pluck(key, config_hash)
end
def section_key(key, components)
- if key =~ /^disable_/ # "disable_httpclient"
+ if /^disable_/.match?(key) # "disable_httpclient"
DISABLING
- elsif components.length >= 2 && !(components[1] == "attributes") # "analytics_events.enabled"
+ elsif components.length >= 2 && !(components[1] == 'attributes') # "analytics_events.enabled"
components.first
- elsif components[1] == "attributes" # "transaction_tracer.attributes.enabled"
+ elsif components[1] == 'attributes' # "transaction_tracer.attributes.enabled"
ATTRIBUTES
else
GENERAL
diff --git a/lib/tasks/helpers/removers.rb b/lib/tasks/helpers/removers.rb
index 9c3c64ec73..50d10304b3 100644
--- a/lib/tasks/helpers/removers.rb
+++ b/lib/tasks/helpers/removers.rb
@@ -11,21 +11,21 @@ def remove_local_multiverse_databases
`echo "drop database #{database}" | mysql -u root`
end
rescue => error
- puts "ERROR: Cannot get MySQL databases..."
+ puts 'ERROR: Cannot get MySQL databases...'
puts error.message
end
def remove_generated_gemfiles
- file_path = File.expand_path("test/multiverse/suites")
- Dir.glob(File.join(file_path, "**", "Gemfile*")).each do |fn|
+ file_path = File.expand_path('test/multiverse/suites')
+ Dir.glob(File.join(file_path, '**', 'Gemfile*')).each do |fn|
puts "Removing #{fn.gsub(file_path, '.../suites')}"
FileUtils.rm(fn)
end
end
def remove_generated_gemfile_lockfiles
- file_path = File.expand_path("test/environments")
- Dir.glob(File.join(file_path, "**", "Gemfile.lock")).each do |fn|
+ file_path = File.expand_path('test/environments')
+ Dir.glob(File.join(file_path, '**', 'Gemfile.lock')).each do |fn|
puts "Removing #{fn.gsub(file_path, '.../environments')}"
FileUtils.rm(fn)
end
diff --git a/lib/tasks/install.rake b/lib/tasks/install.rake
index a85210ca54..7ccb113fa9 100644
--- a/lib/tasks/install.rake
+++ b/lib/tasks/install.rake
@@ -3,13 +3,13 @@
# frozen_string_literal: true
namespace :newrelic do
- desc "Install a default config/newrelic.yml file"
+ desc 'Install a default config/newrelic.yml file'
task :install do
- load File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "install.rb"))
+ load File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'install.rb'))
end
- desc "Gratefulness is always appreciated"
+ desc 'Gratefulness is always appreciated'
task :thanks do
- puts "The Ruby agent team is grateful to Jim Weirich for his kindness and his code. He will be missed."
+ puts 'The Ruby agent team is grateful to Jim Weirich for his kindness and his code. He will be missed.'
end
end
diff --git a/lib/tasks/multiverse.rb b/lib/tasks/multiverse.rb
index 4ec423025f..52536b3cb2 100644
--- a/lib/tasks/multiverse.rb
+++ b/lib/tasks/multiverse.rb
@@ -39,12 +39,14 @@
include Removers
namespace :test do
- desc "Run functional test suite for New Relic"
+ desc 'Run functional test suite for New Relic'
task :multiverse, [:suite, :param1, :param2, :param3, :param4] => ['multiverse:env'] do |_, args|
Multiverse::Runner.run(args.suite, Multiverse::Runner.parse_args(args))
end
namespace :multiverse do
+ # task :prerequisites
+
task :env do
# ENV['SUITES_DIRECTORY'] = File.expand_path('../../test/multiverse/suites', __FILE__)
require File.expand_path('../../../test/multiverse/lib/multiverse', __FILE__)
@@ -56,22 +58,26 @@
remove_generated_gemfile_lockfiles
end
- desc "Clean cached gemfiles from Bundler.bundle_path"
+ desc 'Clean cached gemfiles from Bundler.bundle_path'
task :clean_gemfile_cache do
glob = File.expand_path('multiverse-cache/Gemfile.*.lock', Bundler.bundle_path)
File.delete(*Dir[glob])
end
- desc "Test the multiverse testing framework by executing tests in test/multiverse/test. Get meta with it."
+ desc 'Test the multiverse testing framework by executing tests in test/multiverse/test. Get meta with it.'
task :self, [:suite, :mode] do |_, args|
- args.with_defaults(:suite => "", :mode => "")
- puts ("Testing the multiverse testing framework...")
+ args.with_defaults(:suite => '', :mode => '')
+ puts ('Testing the multiverse testing framework...')
test_files = FileList['test/multiverse/test/*_test.rb']
- ruby test_files.join(" ")
+ ruby test_files.join(' ')
end
task :prime, [:suite] => [:env] do |_, args|
Multiverse::Runner.prime(args.suite, Multiverse::Runner.parse_args(args))
end
+
+ task :gem_manifest => :env do
+ Multiverse::GemManifest.new.report
+ end
end
end
diff --git a/lib/tasks/tests.rake b/lib/tasks/tests.rake
index 9e6bed8922..a86adbab91 100644
--- a/lib/tasks/tests.rake
+++ b/lib/tasks/tests.rake
@@ -13,19 +13,19 @@ end
if defined? Rake::TestTask
namespace :test do
tasks = Rake.application.top_level_tasks
- ENV["TESTOPTS"] ||= ""
- if tasks.any? { |t| t.include?("verbose") }
- ENV["TESTOPTS"] += " -v"
+ ENV['TESTOPTS'] ||= ''
+ if tasks.any? { |t| t.include?('verbose') }
+ ENV['TESTOPTS'] += ' -v'
end
if seed = look_for_seed(tasks)
- ENV["TESTOPTS"] += " --" + seed
+ ENV['TESTOPTS'] += ' --' + seed
end
agent_home = File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
Rake::TestTask.new(:newrelic) do |t|
- file_pattern = ENV["file"]
- file_pattern = file_pattern.split(",").map { |f| "#{agent_home}/#{f}".gsub("//", "/") } if file_pattern
+ file_pattern = ENV['file']
+ file_pattern = file_pattern.split(',').map { |f| "#{agent_home}/#{f}".gsub('//', '/') } if file_pattern
file_pattern ||= "#{agent_home}/test/new_relic/**/*_test.rb"
t.libs << "#{agent_home}/test"
diff --git a/newrelic_rpm.gemspec b/newrelic_rpm.gemspec
index a2a5c5449b..9cb2889314 100644
--- a/newrelic_rpm.gemspec
+++ b/newrelic_rpm.gemspec
@@ -6,11 +6,11 @@ require 'new_relic/version'
require 'new_relic/latest_changes'
Gem::Specification.new do |s|
- s.name = "newrelic_rpm"
+ s.name = 'newrelic_rpm'
s.version = NewRelic::VERSION::STRING
s.required_ruby_version = '>= 2.4.0'
- s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to?(:required_rubygems_version=)
- s.authors = ["Tanna McClure", "Kayla Reopelle", "James Bunch", "Hannah Ramadan"]
+ s.required_rubygems_version = Gem::Requirement.new('> 1.3.1') if s.respond_to?(:required_rubygems_version=)
+ s.authors = ['Tanna McClure', 'Kayla Reopelle', 'James Bunch', 'Hannah Ramadan']
s.licenses = ['Apache-2.0']
s.description = <<~EOS
New Relic is a performance management system, developed by New Relic,
@@ -20,14 +20,14 @@ Gem::Specification.new do |s|
Gem or plugin, hosted on
https://github.com/newrelic/newrelic-ruby-agent/
EOS
- s.email = "support@newrelic.com"
+ s.email = 'support@newrelic.com'
s.executables = %w[newrelic_cmd newrelic nrdebug]
s.extra_rdoc_files = [
- "CHANGELOG.md",
- "LICENSE",
- "README.md",
- "CONTRIBUTING.md",
- "newrelic.yml"
+ 'CHANGELOG.md',
+ 'LICENSE',
+ 'README.md',
+ 'CONTRIBUTING.md',
+ 'newrelic.yml'
]
s.metadata = {
@@ -35,7 +35,7 @@ Gem::Specification.new do |s|
'changelog_uri' => 'https://github.com/newrelic/newrelic-ruby-agent/blob/main/CHANGELOG.md',
'documentation_uri' => 'https://docs.newrelic.com/docs/agents/ruby-agent',
'source_code_uri' => 'https://github.com/newrelic/newrelic-ruby-agent',
- "homepage_uri" => "https://newrelic.com/ruby"
+ 'homepage_uri' => 'https://newrelic.com/ruby'
}
file_list = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features|infinite_tracing|\.github)/(?!agent_helper.rb)}) }
@@ -43,9 +43,9 @@ Gem::Specification.new do |s|
file_list << build_file_path if File.exist?(build_file_path)
s.files = file_list
- s.homepage = "https://github.com/newrelic/rpm"
- s.require_paths = ["lib"]
- s.summary = "New Relic Ruby Agent"
+ s.homepage = 'https://github.com/newrelic/rpm'
+ s.require_paths = ['lib']
+ s.summary = 'New Relic Ruby Agent'
s.add_development_dependency 'bundler'
s.add_development_dependency 'feedjira', '3.2.1' unless ENV['CI'] || RUBY_VERSION < '2.5' # for Gabby
s.add_development_dependency 'httparty' unless ENV['CI'] # for perf tests and Gabby
diff --git a/test/agent_helper.rb b/test/agent_helper.rb
index c8e80b5221..39cf6f4cb8 100644
--- a/test/agent_helper.rb
+++ b/test/agent_helper.rb
@@ -111,7 +111,8 @@ def assert_equal_unordered(left, right)
def assert_log_contains(log, message)
lines = log.array
- assert (lines.any? { |line| line.match(message) })
+ assert (lines.any? { |line| line.match(message) }),
+ "Could not find message. Log contained: #{lines.join("\n")}"
end
def assert_audit_log_contains(audit_log_contents, needle)
@@ -147,7 +148,7 @@ def assert_audit_log_contains_object(audit_log_contents, o, format = :json)
end
when NilClass
- assert_audit_log_contains(audit_log_contents, format == :json ? "null" : "nil")
+ assert_audit_log_contains(audit_log_contents, format == :json ? 'null' : 'nil')
else
assert_audit_log_contains(audit_log_contents, o.inspect)
end
@@ -182,7 +183,7 @@ def _normalize_metric_expectations(expectations)
end
def dump_stats(stats)
- str = String.new(" Call count: #{stats.call_count}\n")
+ str = +" Call count: #{stats.call_count}\n"
str << " Total call time: #{stats.total_call_time}\n"
str << " Total exclusive time: #{stats.total_exclusive_time}\n"
str << " Min call time: #{stats.min_call_time}\n"
@@ -379,8 +380,8 @@ def assert_false(expected)
# in_transaction('foobar', :category => :controller) { ... }
#
def in_transaction(*args, &blk)
- opts = args.last && args.last.is_a?(Hash) ? args.pop : {}
- category = (opts && opts.delete(:category)) || :other
+ opts = args.last&.is_a?(Hash) ? args.pop : {}
+ category = (opts&.delete(:category)) || :other
# At least one test passes `:transaction_name => nil`, so handle it gently
name = opts.key?(:transaction_name) ? opts.delete(:transaction_name) : args.first || 'dummy'
@@ -434,10 +435,10 @@ def capture_segment_with_error
segment_with_error = nil
with_segment do |segment|
segment_with_error = segment
- raise "oops!"
+ raise 'oops!'
end
rescue Exception => exception
- assert segment_with_error, "expected to have a segment_with_error"
+ assert segment_with_error, 'expected to have a segment_with_error'
build_deferred_error_attributes(segment_with_error)
return segment_with_error, exception
end
@@ -476,7 +477,7 @@ def last_transaction_trace
def last_transaction_trace_request_params
agent_attributes = attributes_for(last_transaction_trace, :agent)
agent_attributes.inject({}) do |memo, (key, value)|
- memo[key] = value if key.to_s.start_with?("request.parameters.")
+ memo[key] = value if key.to_s.start_with?('request.parameters.')
memo
end
end
@@ -671,7 +672,7 @@ def undefine_constant(constant_symbol)
const_str = constant_symbol.to_s
parent = get_parent(const_str)
const_name = const_str.gsub(/.*::/, '')
- return yield unless parent && parent.constants.include?(const_name.to_sym)
+ return yield unless parent&.constants&.include?(const_name.to_sym)
removed_constant = parent.send(:remove_const, const_name)
yield
@@ -693,13 +694,13 @@ def with_debug_logging
end
def create_agent_command(args = {})
- NewRelic::Agent::Commands::AgentCommand.new([-1, {"name" => "command_name", "arguments" => args}])
+ NewRelic::Agent::Commands::AgentCommand.new([-1, {'name' => 'command_name', 'arguments' => args}])
end
def wait_for_backtrace_service_poll(opts = {})
defaults = {
:timeout => 10.0,
- :service => NewRelic::Agent.agent.agent_command_router.backtrace_service,
+ :service => NewRelic::Agent.agent.instance_variable_get(:@agent_command_router).backtrace_service,
:iterations => 1
}
opts = defaults.merge(opts)
@@ -729,7 +730,7 @@ def with_array_logger(level = :info)
override_logger = Logger.new(logdev)
with_config(config) do
- NewRelic::Agent.logger = NewRelic::Agent::AgentLogger.new("", override_logger)
+ NewRelic::Agent.logger = NewRelic::Agent::AgentLogger.new('', override_logger)
yield
end
@@ -876,7 +877,7 @@ def load_cross_agent_test(name)
end
def each_cross_agent_test(options)
- options = {:dir => nil, :pattern => "*"}.update(options)
+ options = {:dir => nil, :pattern => '*'}.update(options)
path = File.join([cross_agent_tests_dir, options[:dir], options[:pattern]].compact)
Dir.glob(path).each { |file| yield(file) }
end
@@ -891,7 +892,7 @@ def assert_event_attributes(event, test_name, expected_attributes, non_expected_
incorrect_attributes << name unless actual_value == expected_value
end
- msg = String.new("Found missing or incorrect attribute values in #{test_name}:\n")
+ msg = +"Found missing or incorrect attribute values in #{test_name}:\n"
incorrect_attributes.each do |name|
msg << " #{name}: expected = #{expected_attributes[name].inspect}, actual = #{event_attrs[name].inspect}\n"
@@ -930,10 +931,10 @@ def message_for_status_code(code)
end
case code
- when 200 then "OK"
- when 404 then "Not Found"
- when 403 then "Forbidden"
- else "Unknown"
+ when 200 then 'OK'
+ when 404 then 'Not Found'
+ when 403 then 'Forbidden'
+ else 'Unknown'
end
end
@@ -942,7 +943,7 @@ def message_for_status_code(code)
# a "status_code" may be passed in the headers to alter the HTTP Status Code
# that is wrapped in the response.
def mock_http_response(headers, wrap_it = true)
- status_code = (headers.delete("status_code") || 200).to_i
+ status_code = (headers.delete('status_code') || 200).to_i
net_http_resp = Net::HTTPResponse.new(1.0, status_code, message_for_status_code(status_code))
headers.each do |key, value|
net_http_resp.add_field(key.to_s, value)
@@ -966,7 +967,7 @@ def assert_match_or_equal(expected, value)
def assert_segment_noticed_error(txn, segment_name, error_classes, error_message)
error_segment = txn.segments.reverse.detect { |s| s.noticed_error }
- assert error_segment, "Expected at least one segment with a noticed_error"
+ assert error_segment, 'Expected at least one segment with a noticed_error'
assert_match_or_equal segment_name, error_segment.name
@@ -977,15 +978,15 @@ def assert_segment_noticed_error(txn, segment_name, error_classes, error_message
end
def assert_transaction_noticed_error(txn, error_classes)
- refute_empty txn.exceptions, "Expected transaction to notice the error"
+ refute_empty txn.exceptions, 'Expected transaction to notice the error'
assert_match_or_equal error_classes, txn.exceptions.keys.first.class.name
end
def refute_transaction_noticed_error(txn, error_class)
error_segment = txn.segments.reverse.detect { |s| s.noticed_error }
- assert error_segment, "Expected at least one segment with a noticed_error"
- assert_empty txn.exceptions, "Expected transaction to NOT notice any segment errors"
+ assert error_segment, 'Expected at least one segment with a noticed_error'
+ assert_empty txn.exceptions, 'Expected transaction to NOT notice any segment errors'
end
def refute_raises(*exp)
@@ -1021,6 +1022,6 @@ def defer_testing_to_min_supported_rails(test_file, min_rails_version, supports_
yield
else
- puts "Skipping tests in #{File.basename(test_file)} because Rails >= #{min_rails_version} is unavailable" if ENV["VERBOSE_TEST_OUTPUT"]
+ puts "Skipping tests in #{File.basename(test_file)} because Rails >= #{min_rails_version} is unavailable" if ENV['VERBOSE_TEST_OUTPUT']
end
end
diff --git a/test/environments/lib/environments/runner.rb b/test/environments/lib/environments/runner.rb
index 83166e2506..02071b5224 100644
--- a/test/environments/lib/environments/runner.rb
+++ b/test/environments/lib/environments/runner.rb
@@ -24,14 +24,14 @@ def run_and_report
overall_status = 0
failures = []
- puts yellow("Tests to run:\n\t#{tests_to_run.map { |s| s.gsub(env_root + "/", "") }.join("\n\t")}") if ENV['VERBOSE_TEST_OUTPUT']
- env_file = ENV["file"]
+ puts yellow("Tests to run:\n\t#{tests_to_run.map { |s| s.gsub(env_root + '/', '') }.join("\n\t")}") if ENV['VERBOSE_TEST_OUTPUT']
+ env_file = ENV['file']
tests_to_run.each do |dir|
Bundler.with_unbundled_env do
- ENV["file"] = env_file if env_file
+ ENV['file'] = env_file if env_file
dir = File.expand_path(dir)
- puts "", yellow("Running tests for #{dir}") if ENV['VERBOSE_TEST_OUTPUT']
+ puts '', yellow("Running tests for #{dir}") if ENV['VERBOSE_TEST_OUTPUT']
status = bundle(dir)
status = run(dir) if status.success?
@@ -43,16 +43,16 @@ def run_and_report
end
if overall_status == 0
- puts green("All good to go. Yippy!")
+ puts green('All good to go. Yippy!')
else
- puts red("Oh no, #{overall_status} environments failed!"), "", red(failures.join("\n"))
+ puts red("Oh no, #{overall_status} environments failed!"), '', red(failures.join("\n"))
end
exit(overall_status)
end
def tests_to_run
- original_dirs = Dir["#{env_root}/*"].reject { |d| File.basename(d) == "lib" }
+ original_dirs = Dir["#{env_root}/*"].reject { |d| File.basename(d) == 'lib' }
return original_dirs if envs.empty?
@@ -65,18 +65,18 @@ def tests_to_run
# Ensures we bundle will recognize an explicit version number on command line
def safe_explicit(version)
- return version if version.to_s == ""
+ return version if version.to_s == ''
test_version = `bundle #{version} --version`.include?('Could not find command')
- test_version ? "" : version
+ test_version ? '' : version
end
def explicit_bundler_version(dir)
return if RUBY_PLATFORM == 'java'
- fn = File.join(dir, ".bundler-version")
+ fn = File.join(dir, '.bundler-version')
version = File.exist?(fn) ? File.read(fn).chomp!.strip : nil
- safe_explicit(version.to_s == "" ? nil : "_#{version}_")
+ safe_explicit(version.to_s == '' ? nil : "_#{version}_")
end
def bundle_config(dir, bundle_cmd)
@@ -93,16 +93,16 @@ def bundle(dir)
result = Multiverse::ShellUtils.try_command_n_times(command, 3)
result = red(result) unless $?.success?
- puts result if ENV["VERBOSE_TEST_OUTPUT"]
+ puts result if ENV['VERBOSE_TEST_OUTPUT']
$?
end
def run(dir)
puts "Starting tests for dir '#{dir}'..." if ENV['VERBOSE_TEST_OUTPUT']
- cmd = String.new("cd #{dir} && bundle exec rake")
+ cmd = +"cd #{dir} && bundle exec rake"
# if the shell running the original test:env rake task has a "file" env
# var, replicate it here in the subshell
- cmd << " file=#{ENV['file']}" if ENV["file"]
+ cmd << " file=#{ENV['file']}" if ENV['file']
# if the shell running the original test:env rake task has CLI args (not
# Rake task args) such as '--trace', replicate them here in the subshell
cmd << " #{ARGV[1..-1].join(' ')}" if ARGV.size > 1
diff --git a/test/environments/norails/Gemfile b/test/environments/norails/Gemfile
index 2b931df0d9..0bcf811586 100644
--- a/test/environments/norails/Gemfile
+++ b/test/environments/norails/Gemfile
@@ -13,6 +13,6 @@ gem 'newrelic_rpm', :path => '../../..'
gem 'pry', '~> 0.14.1'
gem 'pry-nav'
-gem 'simplecov' if ENV["VERBOSE_TEST_OUTPUT"]
+gem 'simplecov' if ENV['VERBOSE_TEST_OUTPUT']
gem 'warning' if RUBY_VERSION >= '2.4.0'
diff --git a/test/environments/norails/Rakefile b/test/environments/norails/Rakefile
index 4c43851f2f..d15efb4d93 100644
--- a/test/environments/norails/Rakefile
+++ b/test/environments/norails/Rakefile
@@ -10,6 +10,6 @@ require_relative '../../warning_test_helper'
require 'rake'
require 'tasks/all'
-ENV["NO_RAILS"] = "1"
+ENV['NO_RAILS'] = '1'
task :default => [:'test:newrelic']
diff --git a/test/environments/rails32/.bundler-version b/test/environments/rails32/.bundler-version
deleted file mode 100644
index b9a05a6dc1..0000000000
--- a/test/environments/rails32/.bundler-version
+++ /dev/null
@@ -1 +0,0 @@
-1.17.3
diff --git a/test/environments/rails32/Gemfile b/test/environments/rails32/Gemfile
deleted file mode 100644
index 5900207cca..0000000000
--- a/test/environments/rails32/Gemfile
+++ /dev/null
@@ -1,26 +0,0 @@
-# frozen_string_literal: true
-source 'https://rubygems.org'
-
-gem 'rails', '~> 3.2.0'
-gem 'i18n', '0.6.11'
-gem 'rake', '~> 12.3.3'
-gem 'minitest', '4.7.5' # Minitest ~> 4.2 required for Rails 3.2
-gem 'minitest-stub-const', '~> 0.6'
-gem 'mocha', '~> 1.16', :require => false
-gem 'rack', '< 2.0.0'
-gem 'rack-test'
-
-gem "newrelic_rpm", :path => "../../.."
-
-platforms :jruby do
- gem "activerecord-jdbcmysql-adapter"
- gem "activerecord-jdbcsqlite3-adapter"
-end
-
-platforms :ruby, :rbx do
- gem "mysql2", '~> 0.3.10'
- gem 'sqlite3', '~> 1.3.13'
-end
-
-gem 'pry', '~> 0.9.12'
-gem 'warning' if RUBY_VERSION >= '2.4.0'
diff --git a/test/environments/rails32/Rakefile b/test/environments/rails32/Rakefile
deleted file mode 100644
index fb23b18f14..0000000000
--- a/test/environments/rails32/Rakefile
+++ /dev/null
@@ -1,17 +0,0 @@
-# This file is distributed under New Relic's license terms.
-# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
-# frozen_string_literal: true
-
-# Add your own tasks in files placed in lib/tasks ending in .rake,
-# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
-
-require_relative '../../warning_test_helper'
-require_relative 'config/application'
-require 'rake'
-
-RpmTestApp::Application.load_tasks
-require 'tasks/all'
-
-Rake::Task["default"].clear
-task :default => [:'test:newrelic_with_db']
-task :'test:newrelic_with_db' => [:'db:create', :'test:newrelic']
diff --git a/test/environments/rails32/config/application.rb b/test/environments/rails32/config/application.rb
deleted file mode 100644
index 3d090d8975..0000000000
--- a/test/environments/rails32/config/application.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-# This file is distributed under New Relic's license terms.
-# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
-# frozen_string_literal: true
-
-require_relative 'boot'
-
-require 'rails/all'
-
-Bundler.require(:default, Rails.env) if defined?(Bundler)
-
-module RpmTestApp
- class Application < Rails::Application
- config.encoding = "utf-8"
- config.filter_parameters += [:password]
- config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e'
- config.active_support.deprecation = :notify
- config.eager_load = false
- end
-end
diff --git a/test/environments/rails32/config/boot.rb b/test/environments/rails32/config/boot.rb
deleted file mode 100644
index 00857d182a..0000000000
--- a/test/environments/rails32/config/boot.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-# This file is distributed under New Relic's license terms.
-# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
-# frozen_string_literal: true
-
-require 'rubygems'
-
-# Set up gems listed in the Gemfile.
-ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
-
-require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
diff --git a/test/environments/rails32/config/database.yml b/test/environments/rails32/config/database.yml
deleted file mode 100644
index 8d7abf9da6..0000000000
--- a/test/environments/rails32/config/database.yml
+++ /dev/null
@@ -1,26 +0,0 @@
-mysql: &mysql
- adapter: mysql2
- username: root
- password: <%= ENV['MYSQL_PASSWORD'] %>
- host: localhost
- database: <%= db = "#{ENV['RUBY_VERSION']}#{ENV['BRANCH']}"; db.empty? ? "rails_blog" : db %>
-
-sqlite3: &sqlite3
-<% if defined?(JRuby) %>
- adapter: jdbcsqlite3
-<% else %>
- adapter: sqlite3
-<% end %>
- database: db/all.sqlite3
- pool: 5
- timeout: 5000
- host: localhost
-
-development:
- <<: *sqlite3
-
-test:
- <<: *mysql
-
-production:
- <<: *mysql
diff --git a/test/environments/rails32/config/environment.rb b/test/environments/rails32/config/environment.rb
deleted file mode 100644
index 75ed67ed20..0000000000
--- a/test/environments/rails32/config/environment.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-# This file is distributed under New Relic's license terms.
-# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
-# frozen_string_literal: true
-
-require_relative 'application'
-RpmTestApp::Application.initialize!
diff --git a/test/environments/rails32/db/schema.rb b/test/environments/rails32/db/schema.rb
deleted file mode 100644
index 2d964da716..0000000000
--- a/test/environments/rails32/db/schema.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-# This file is distributed under New Relic's license terms.
-# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
-# frozen_string_literal: true
-
-# File is required to exist by Rails
diff --git a/test/environments/rails40/Rakefile b/test/environments/rails40/Rakefile
index 42acaf4061..23b5351403 100644
--- a/test/environments/rails40/Rakefile
+++ b/test/environments/rails40/Rakefile
@@ -13,5 +13,5 @@ require 'rake'
RpmTestApp::Application.load_tasks
require 'tasks/all'
-Rake::Task["default"].clear
+Rake::Task['default'].clear
task :default => [:'test:newrelic']
diff --git a/test/environments/rails40/config/application.rb b/test/environments/rails40/config/application.rb
index eb82b81f75..e0427038e0 100644
--- a/test/environments/rails40/config/application.rb
+++ b/test/environments/rails40/config/application.rb
@@ -10,7 +10,7 @@
module RpmTestApp
class Application < Rails::Application
- config.encoding = "utf-8"
+ config.encoding = 'utf-8'
config.filter_parameters += [:password]
config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e'
config.eager_load = false
diff --git a/test/environments/rails40/config/initializers/test.rb b/test/environments/rails40/config/initializers/test.rb
index 1d88e77b0a..9981aac1a3 100644
--- a/test/environments/rails40/config/initializers/test.rb
+++ b/test/environments/rails40/config/initializers/test.rb
@@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base
include ::NewRelic::Agent::MethodTracer
def sniff
- puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \
+ puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \
"air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \
- "scent receptors. " \
- "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/"
+ 'scent receptors. ' \
+ 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/'
end
add_method_tracer :sniff
diff --git a/test/environments/rails41/Gemfile b/test/environments/rails41/Gemfile
index c5b7e97155..db9edabac2 100644
--- a/test/environments/rails41/Gemfile
+++ b/test/environments/rails41/Gemfile
@@ -11,16 +11,16 @@ gem 'rack', '~> 1.5.2'
gem 'rack-test'
platforms :jruby do
- gem "activerecord-jdbcmysql-adapter", "~>1.3.0"
- gem "activerecord-jdbcsqlite3-adapter", "~>1.3.0"
+ gem 'activerecord-jdbcmysql-adapter', '~>1.3.0'
+ gem 'activerecord-jdbcsqlite3-adapter', '~>1.3.0'
end
platforms :ruby do
- gem "mysql2", '~> 0.3.20'
+ gem 'mysql2', '~> 0.3.20'
gem 'sqlite3', '~> 1.3.13'
end
-gem "newrelic_rpm", :path => "../../.."
+gem 'newrelic_rpm', :path => '../../..'
gem 'pry', '~> 0.9.12'
gem 'warning' if RUBY_VERSION >= '2.4.0'
diff --git a/test/environments/rails41/Rakefile b/test/environments/rails41/Rakefile
index 42acaf4061..23b5351403 100644
--- a/test/environments/rails41/Rakefile
+++ b/test/environments/rails41/Rakefile
@@ -13,5 +13,5 @@ require 'rake'
RpmTestApp::Application.load_tasks
require 'tasks/all'
-Rake::Task["default"].clear
+Rake::Task['default'].clear
task :default => [:'test:newrelic']
diff --git a/test/environments/rails41/config/application.rb b/test/environments/rails41/config/application.rb
index eb82b81f75..e0427038e0 100644
--- a/test/environments/rails41/config/application.rb
+++ b/test/environments/rails41/config/application.rb
@@ -10,7 +10,7 @@
module RpmTestApp
class Application < Rails::Application
- config.encoding = "utf-8"
+ config.encoding = 'utf-8'
config.filter_parameters += [:password]
config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e'
config.eager_load = false
diff --git a/test/environments/rails41/config/initializers/test.rb b/test/environments/rails41/config/initializers/test.rb
index 06be89db54..b2c0d06c23 100644
--- a/test/environments/rails41/config/initializers/test.rb
+++ b/test/environments/rails41/config/initializers/test.rb
@@ -8,9 +8,9 @@ class Bloodhound < ActiveRecord::Base
include ::NewRelic::Agent::MethodTracer
def sniff
- puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject)," \
+ puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject),' \
"air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's scent receptors. " \
- "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/"
+ 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/'
end
add_method_tracer :sniff
diff --git a/test/environments/rails42/Gemfile b/test/environments/rails42/Gemfile
index 7a5282de78..c3a8e99d88 100644
--- a/test/environments/rails42/Gemfile
+++ b/test/environments/rails42/Gemfile
@@ -13,16 +13,16 @@ gem 'rack-test'
gem 'sprockets', '3.7.2'
platforms :jruby do
- gem "activerecord-jdbcmysql-adapter", "~>1.3.0"
- gem "activerecord-jdbcsqlite3-adapter", "~>1.3.0"
+ gem 'activerecord-jdbcmysql-adapter', '~>1.3.0'
+ gem 'activerecord-jdbcsqlite3-adapter', '~>1.3.0'
end
platforms :ruby, :rbx do
- gem "mysql2"
+ gem 'mysql2'
gem 'sqlite3', '~> 1.3.13'
end
-gem "newrelic_rpm", :path => "../../.."
+gem 'newrelic_rpm', :path => '../../..'
gem 'pry', '~> 0.12.2'
gem 'pry-nav'
diff --git a/test/environments/rails42/Rakefile b/test/environments/rails42/Rakefile
index 42acaf4061..23b5351403 100644
--- a/test/environments/rails42/Rakefile
+++ b/test/environments/rails42/Rakefile
@@ -13,5 +13,5 @@ require 'rake'
RpmTestApp::Application.load_tasks
require 'tasks/all'
-Rake::Task["default"].clear
+Rake::Task['default'].clear
task :default => [:'test:newrelic']
diff --git a/test/environments/rails42/config/application.rb b/test/environments/rails42/config/application.rb
index eb82b81f75..e0427038e0 100644
--- a/test/environments/rails42/config/application.rb
+++ b/test/environments/rails42/config/application.rb
@@ -10,7 +10,7 @@
module RpmTestApp
class Application < Rails::Application
- config.encoding = "utf-8"
+ config.encoding = 'utf-8'
config.filter_parameters += [:password]
config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e'
config.eager_load = false
diff --git a/test/environments/rails42/config/initializers/test.rb b/test/environments/rails42/config/initializers/test.rb
index 1d88e77b0a..9981aac1a3 100644
--- a/test/environments/rails42/config/initializers/test.rb
+++ b/test/environments/rails42/config/initializers/test.rb
@@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base
include ::NewRelic::Agent::MethodTracer
def sniff
- puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \
+ puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \
"air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \
- "scent receptors. " \
- "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/"
+ 'scent receptors. ' \
+ 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/'
end
add_method_tracer :sniff
diff --git a/test/environments/rails50/Gemfile b/test/environments/rails50/Gemfile
index 2eec576c15..b887840b89 100644
--- a/test/environments/rails50/Gemfile
+++ b/test/environments/rails50/Gemfile
@@ -13,16 +13,16 @@ gem 'rack-test'
gem 'sprockets', '3.7.2'
platforms :jruby do
- gem "activerecord-jdbcmysql-adapter", "~> 50.0"
- gem "activerecord-jdbcsqlite3-adapter", "~> 50.0"
+ gem 'activerecord-jdbcmysql-adapter', '~> 50.0'
+ gem 'activerecord-jdbcsqlite3-adapter', '~> 50.0'
end
platforms :ruby, :rbx do
- gem "mysql2"
+ gem 'mysql2'
gem 'sqlite3', '~> 1.3.13'
end
-gem "newrelic_rpm", :path => "../../.."
+gem 'newrelic_rpm', :path => '../../..'
gem 'pry', '~> 0.12.2'
gem 'pry-nav'
diff --git a/test/environments/rails50/Rakefile b/test/environments/rails50/Rakefile
index 42acaf4061..23b5351403 100644
--- a/test/environments/rails50/Rakefile
+++ b/test/environments/rails50/Rakefile
@@ -13,5 +13,5 @@ require 'rake'
RpmTestApp::Application.load_tasks
require 'tasks/all'
-Rake::Task["default"].clear
+Rake::Task['default'].clear
task :default => [:'test:newrelic']
diff --git a/test/environments/rails50/config/application.rb b/test/environments/rails50/config/application.rb
index eb82b81f75..e0427038e0 100644
--- a/test/environments/rails50/config/application.rb
+++ b/test/environments/rails50/config/application.rb
@@ -10,7 +10,7 @@
module RpmTestApp
class Application < Rails::Application
- config.encoding = "utf-8"
+ config.encoding = 'utf-8'
config.filter_parameters += [:password]
config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e'
config.eager_load = false
diff --git a/test/environments/rails50/config/initializers/test.rb b/test/environments/rails50/config/initializers/test.rb
index 1d88e77b0a..9981aac1a3 100644
--- a/test/environments/rails50/config/initializers/test.rb
+++ b/test/environments/rails50/config/initializers/test.rb
@@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base
include ::NewRelic::Agent::MethodTracer
def sniff
- puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \
+ puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \
"air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \
- "scent receptors. " \
- "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/"
+ 'scent receptors. ' \
+ 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/'
end
add_method_tracer :sniff
diff --git a/test/environments/rails51/Gemfile b/test/environments/rails51/Gemfile
index 75e9578dcc..50c0d6fb58 100644
--- a/test/environments/rails51/Gemfile
+++ b/test/environments/rails51/Gemfile
@@ -12,16 +12,16 @@ gem 'rack-test'
gem 'sprockets', '3.7.2'
platforms :jruby do
- gem "activerecord-jdbcmysql-adapter", "~> 51.0"
- gem "activerecord-jdbcsqlite3-adapter", "~> 51.0"
+ gem 'activerecord-jdbcmysql-adapter', '~> 51.0'
+ gem 'activerecord-jdbcsqlite3-adapter', '~> 51.0'
end
platforms :ruby, :rbx do
- gem "mysql2"
+ gem 'mysql2'
gem 'sqlite3', '~> 1.3.13'
end
-gem "newrelic_rpm", :path => "../../.."
+gem 'newrelic_rpm', :path => '../../..'
gem 'pry', '~> 0.12.2'
gem 'pry-nav'
diff --git a/test/environments/rails51/Rakefile b/test/environments/rails51/Rakefile
index 4e16c4f323..716450b039 100644
--- a/test/environments/rails51/Rakefile
+++ b/test/environments/rails51/Rakefile
@@ -11,5 +11,5 @@ require 'rake'
RpmTestApp::Application.load_tasks
require 'tasks/all'
-Rake::Task["default"].clear
+Rake::Task['default'].clear
task :default => [:'test:newrelic']
diff --git a/test/environments/rails51/config/application.rb b/test/environments/rails51/config/application.rb
index eb82b81f75..e0427038e0 100644
--- a/test/environments/rails51/config/application.rb
+++ b/test/environments/rails51/config/application.rb
@@ -10,7 +10,7 @@
module RpmTestApp
class Application < Rails::Application
- config.encoding = "utf-8"
+ config.encoding = 'utf-8'
config.filter_parameters += [:password]
config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e'
config.eager_load = false
diff --git a/test/environments/rails51/config/initializers/test.rb b/test/environments/rails51/config/initializers/test.rb
index 1d88e77b0a..9981aac1a3 100644
--- a/test/environments/rails51/config/initializers/test.rb
+++ b/test/environments/rails51/config/initializers/test.rb
@@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base
include ::NewRelic::Agent::MethodTracer
def sniff
- puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \
+ puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \
"air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \
- "scent receptors. " \
- "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/"
+ 'scent receptors. ' \
+ 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/'
end
add_method_tracer :sniff
diff --git a/test/environments/rails52/Gemfile b/test/environments/rails52/Gemfile
index 88ebe8f763..4b8916b9f1 100644
--- a/test/environments/rails52/Gemfile
+++ b/test/environments/rails52/Gemfile
@@ -12,8 +12,8 @@ gem 'rack-test'
gem 'sprockets', '3.7.2'
platforms :jruby do
- gem "activerecord-jdbcmysql-adapter", "~> 52.0"
- gem "activerecord-jdbcsqlite3-adapter", "~> 52.0"
+ gem 'activerecord-jdbcmysql-adapter', '~> 52.0'
+ gem 'activerecord-jdbcsqlite3-adapter', '~> 52.0'
end
platforms :ruby, :rbx do
@@ -21,7 +21,7 @@ platforms :ruby, :rbx do
gem 'sqlite3', '~> 1.3.13'
end
-gem 'newrelic_rpm', :path => "../../.."
+gem 'newrelic_rpm', :path => '../../..'
gem 'pry', '~> 0.12.2'
gem 'pry-nav'
diff --git a/test/environments/rails52/Rakefile b/test/environments/rails52/Rakefile
index 42acaf4061..23b5351403 100644
--- a/test/environments/rails52/Rakefile
+++ b/test/environments/rails52/Rakefile
@@ -13,5 +13,5 @@ require 'rake'
RpmTestApp::Application.load_tasks
require 'tasks/all'
-Rake::Task["default"].clear
+Rake::Task['default'].clear
task :default => [:'test:newrelic']
diff --git a/test/environments/rails52/config/application.rb b/test/environments/rails52/config/application.rb
index 004028ff9f..c4535fb6c6 100644
--- a/test/environments/rails52/config/application.rb
+++ b/test/environments/rails52/config/application.rb
@@ -11,7 +11,7 @@
module RpmTestApp
class Application < Rails::Application
- config.encoding = "utf-8"
+ config.encoding = 'utf-8'
config.active_record.sqlite3.represent_boolean_as_integer = true
config.filter_parameters += [:password]
config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e'
diff --git a/test/environments/rails52/config/initializers/test.rb b/test/environments/rails52/config/initializers/test.rb
index 1d88e77b0a..9981aac1a3 100644
--- a/test/environments/rails52/config/initializers/test.rb
+++ b/test/environments/rails52/config/initializers/test.rb
@@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base
include ::NewRelic::Agent::MethodTracer
def sniff
- puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \
+ puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \
"air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \
- "scent receptors. " \
- "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/"
+ 'scent receptors. ' \
+ 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/'
end
add_method_tracer :sniff
diff --git a/test/environments/rails60/Gemfile b/test/environments/rails60/Gemfile
index 7c8cd74afc..6bfbaf6a5e 100644
--- a/test/environments/rails60/Gemfile
+++ b/test/environments/rails60/Gemfile
@@ -13,12 +13,12 @@ gem 'rack-test'
gem 'sprockets', '3.7.2'
platforms :jruby do
- gem "activerecord-jdbcmysql-adapter", "~> 60.0"
- gem "activerecord-jdbcsqlite3-adapter", "~> 60.0"
+ gem 'activerecord-jdbcmysql-adapter', '~> 60.0'
+ gem 'activerecord-jdbcsqlite3-adapter', '~> 60.0'
end
platforms :ruby, :rbx do
- gem "mysql2", '>= 0.5.4'
+ gem 'mysql2', '>= 0.5.4'
if RUBY_VERSION < '2.6'
gem 'sqlite3', '~> 1.4.0'
elsif RUBY_VERSION < '2.7'
@@ -28,9 +28,9 @@ platforms :ruby, :rbx do
end
end
-gem "newrelic_rpm", :path => "../../.."
+gem 'newrelic_rpm', :path => '../../..'
gem 'pry', '~> 0.14.1'
gem 'pry-nav'
-gem 'simplecov' if ENV["VERBOSE_TEST_OUTPUT"]
+gem 'simplecov' if ENV['VERBOSE_TEST_OUTPUT']
gem 'warning' if RUBY_VERSION >= '2.4.0'
diff --git a/test/environments/rails60/Rakefile b/test/environments/rails60/Rakefile
index 42acaf4061..23b5351403 100644
--- a/test/environments/rails60/Rakefile
+++ b/test/environments/rails60/Rakefile
@@ -13,5 +13,5 @@ require 'rake'
RpmTestApp::Application.load_tasks
require 'tasks/all'
-Rake::Task["default"].clear
+Rake::Task['default'].clear
task :default => [:'test:newrelic']
diff --git a/test/environments/rails60/config/application.rb b/test/environments/rails60/config/application.rb
index f9e971b51d..3d231afcf4 100644
--- a/test/environments/rails60/config/application.rb
+++ b/test/environments/rails60/config/application.rb
@@ -16,7 +16,7 @@
module RpmTestApp
class Application < Rails::Application
- config.encoding = "utf-8"
+ config.encoding = 'utf-8'
config.filter_parameters += [:password]
config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e'
config.eager_load = false
diff --git a/test/environments/rails60/config/initializers/test.rb b/test/environments/rails60/config/initializers/test.rb
index 1d88e77b0a..9981aac1a3 100644
--- a/test/environments/rails60/config/initializers/test.rb
+++ b/test/environments/rails60/config/initializers/test.rb
@@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base
include ::NewRelic::Agent::MethodTracer
def sniff
- puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \
+ puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \
"air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \
- "scent receptors. " \
- "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/"
+ 'scent receptors. ' \
+ 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/'
end
add_method_tracer :sniff
diff --git a/test/environments/rails60/config/psych4_monkeypatch.rb b/test/environments/rails60/config/psych4_monkeypatch.rb
index dab4849946..706390de26 100644
--- a/test/environments/rails60/config/psych4_monkeypatch.rb
+++ b/test/environments/rails60/config/psych4_monkeypatch.rb
@@ -14,34 +14,34 @@ module Rails
class Application
class Configuration < ::Rails::Engine::Configuration
def database_configuration
- path = paths["config/database"].existent.first
+ path = paths['config/database'].existent.first
yaml = Pathname.new(path) if path
- config = if yaml && yaml.exist?
- require "yaml"
- require "erb"
+ config = if yaml&.exist?
+ require 'yaml'
+ require 'erb'
# THIS LINE CHANGED
# loaded_yaml = YAML.load(ERB.new(yaml.read).result) || {}
loaded_yaml = YAML.unsafe_load(ERB.new(yaml.read).result) || {}
- shared = loaded_yaml.delete("shared")
+ shared = loaded_yaml.delete('shared')
if shared
loaded_yaml.each do |_k, values|
values.reverse_merge!(shared)
end
end
Hash.new(shared).merge(loaded_yaml)
- elsif ENV["DATABASE_URL"]
+ elsif ENV['DATABASE_URL']
{}
else
- raise "Could not load database configuration. No such file - #{paths["config/database"].instance_variable_get(:@paths)}"
+ raise "Could not load database configuration. No such file - #{paths['config/database'].instance_variable_get(:@paths)}"
end
config
rescue Psych::SyntaxError => e
- raise "YAML syntax error occurred while parsing #{paths["config/database"].first}. " \
- "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
+ raise "YAML syntax error occurred while parsing #{paths['config/database'].first}. " \
+ 'Please note that YAML must be consistently indented using spaces. Tabs are not allowed. ' \
"Error: #{e.message}"
rescue => e
raise e, "Cannot load database configuration:\n#{e.message}", e.backtrace
diff --git a/test/environments/rails61/Gemfile b/test/environments/rails61/Gemfile
index 40de29dcb4..08486cbe07 100644
--- a/test/environments/rails61/Gemfile
+++ b/test/environments/rails61/Gemfile
@@ -12,8 +12,8 @@ gem 'rack-test'
gem 'sprockets', '3.7.2'
platforms :jruby do
- gem "activerecord-jdbcmysql-adapter", "~> 61.0"
- gem "activerecord-jdbcsqlite3-adapter", "~> 61.0"
+ gem 'activerecord-jdbcmysql-adapter', '~> 61.0'
+ gem 'activerecord-jdbcsqlite3-adapter', '~> 61.0'
end
platforms :ruby, :rbx do
@@ -31,5 +31,5 @@ gem 'newrelic_rpm', path: '../../..'
gem 'pry', '~> 0.14.1'
gem 'pry-nav'
-gem 'simplecov' if ENV["VERBOSE_TEST_OUTPUT"]
+gem 'simplecov' if ENV['VERBOSE_TEST_OUTPUT']
gem 'warning' if RUBY_VERSION >= '2.4.0'
diff --git a/test/environments/rails61/Rakefile b/test/environments/rails61/Rakefile
index b54e9115f5..8723f412b9 100644
--- a/test/environments/rails61/Rakefile
+++ b/test/environments/rails61/Rakefile
@@ -13,5 +13,5 @@ require 'rake'
RpmTestApp::Application.load_tasks
require 'tasks/all'
-Rake::Task["default"].clear
+Rake::Task['default'].clear
task :default => [:'test:newrelic']
diff --git a/test/environments/rails61/config/application.rb b/test/environments/rails61/config/application.rb
index 9c9b5c07ba..47b5b8020f 100644
--- a/test/environments/rails61/config/application.rb
+++ b/test/environments/rails61/config/application.rb
@@ -11,7 +11,7 @@
module RpmTestApp
class Application < Rails::Application
- config.encoding = "utf-8"
+ config.encoding = 'utf-8'
config.filter_parameters += [:password]
config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e'
config.eager_load = false
diff --git a/test/environments/rails61/config/initializers/test.rb b/test/environments/rails61/config/initializers/test.rb
index 1d88e77b0a..9981aac1a3 100644
--- a/test/environments/rails61/config/initializers/test.rb
+++ b/test/environments/rails61/config/initializers/test.rb
@@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base
include ::NewRelic::Agent::MethodTracer
def sniff
- puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \
+ puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \
"air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \
- "scent receptors. " \
- "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/"
+ 'scent receptors. ' \
+ 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/'
end
add_method_tracer :sniff
diff --git a/test/environments/rails70/Gemfile b/test/environments/rails70/Gemfile
index d4593b99c0..b4733517ef 100644
--- a/test/environments/rails70/Gemfile
+++ b/test/environments/rails70/Gemfile
@@ -2,7 +2,7 @@
source 'https://rubygems.org'
gem 'rails', '~> 7.0.4'
-gem "bootsnap", ">= 1.4.4", require: false
+gem 'bootsnap', '>= 1.4.4', require: false
gem 'minitest', '5.2.3'
gem 'minitest-stub-const', '~> 0.6'
@@ -17,5 +17,5 @@ gem 'newrelic_rpm', path: '../../..'
gem 'pry', '~> 0.14.1'
gem 'pry-nav'
-gem 'simplecov' if ENV["VERBOSE_TEST_OUTPUT"]
+gem 'simplecov' if ENV['VERBOSE_TEST_OUTPUT']
gem 'warning' if RUBY_VERSION >= '2.4.0'
diff --git a/test/environments/rails70/Rakefile b/test/environments/rails70/Rakefile
index 525c85931c..8c74a5a9a9 100644
--- a/test/environments/rails70/Rakefile
+++ b/test/environments/rails70/Rakefile
@@ -13,5 +13,5 @@ Rails.application.load_tasks
require 'tasks/all'
-Rake::Task["default"].clear
+Rake::Task['default'].clear
task :default => [:'test:newrelic']
diff --git a/test/environments/rails70/config/boot.rb b/test/environments/rails70/config/boot.rb
index 30155f0617..a8d25cb53d 100644
--- a/test/environments/rails70/config/boot.rb
+++ b/test/environments/rails70/config/boot.rb
@@ -2,7 +2,7 @@
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
# frozen_string_literal: true
-ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
-require "bundler/setup" # Set up gems listed in the Gemfile.
-require "bootsnap/setup" # Speed up boot time by caching expensive operations.
+require 'bundler/setup' # Set up gems listed in the Gemfile.
+require 'bootsnap/setup' # Speed up boot time by caching expensive operations.
diff --git a/test/environments/rails70/config/initializers/test.rb b/test/environments/rails70/config/initializers/test.rb
index 1d88e77b0a..9981aac1a3 100644
--- a/test/environments/rails70/config/initializers/test.rb
+++ b/test/environments/rails70/config/initializers/test.rb
@@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base
include ::NewRelic::Agent::MethodTracer
def sniff
- puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \
+ puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \
"air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \
- "scent receptors. " \
- "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/"
+ 'scent receptors. ' \
+ 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/'
end
add_method_tracer :sniff
diff --git a/test/environments/railsedge/Gemfile b/test/environments/railsedge/Gemfile
index 2ba0840b06..82aab5b670 100644
--- a/test/environments/railsedge/Gemfile
+++ b/test/environments/railsedge/Gemfile
@@ -2,7 +2,7 @@
source 'https://rubygems.org'
gem 'rails', git: 'https://github.com/rails/rails.git', branch: 'main'
-gem "bootsnap", ">= 1.4.4", require: false
+gem 'bootsnap', '>= 1.4.4', require: false
gem 'minitest', '5.2.3'
gem 'minitest-stub-const', '~> 0.6'
@@ -17,5 +17,5 @@ gem 'newrelic_rpm', path: '../../..'
gem 'pry', '~> 0.14.1'
gem 'pry-nav'
-gem 'simplecov' if ENV["VERBOSE_TEST_OUTPUT"]
+gem 'simplecov' if ENV['VERBOSE_TEST_OUTPUT']
gem 'warning' if RUBY_VERSION >= '2.4.0'
diff --git a/test/environments/railsedge/Rakefile b/test/environments/railsedge/Rakefile
index 1a559d41a9..8c74a5a9a9 100644
--- a/test/environments/railsedge/Rakefile
+++ b/test/environments/railsedge/Rakefile
@@ -7,11 +7,11 @@
require_relative '../../warning_test_helper'
-require_relative "config/application"
+require_relative 'config/application'
Rails.application.load_tasks
require 'tasks/all'
-Rake::Task["default"].clear
+Rake::Task['default'].clear
task :default => [:'test:newrelic']
diff --git a/test/environments/railsedge/config/application.rb b/test/environments/railsedge/config/application.rb
index 29b647d892..2565b8762e 100644
--- a/test/environments/railsedge/config/application.rb
+++ b/test/environments/railsedge/config/application.rb
@@ -2,9 +2,9 @@
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
# frozen_string_literal: true
-require_relative "boot"
+require_relative 'boot'
-require "rails/all"
+require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
diff --git a/test/environments/railsedge/config/boot.rb b/test/environments/railsedge/config/boot.rb
index 30155f0617..a8d25cb53d 100644
--- a/test/environments/railsedge/config/boot.rb
+++ b/test/environments/railsedge/config/boot.rb
@@ -2,7 +2,7 @@
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
# frozen_string_literal: true
-ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
-require "bundler/setup" # Set up gems listed in the Gemfile.
-require "bootsnap/setup" # Speed up boot time by caching expensive operations.
+require 'bundler/setup' # Set up gems listed in the Gemfile.
+require 'bootsnap/setup' # Speed up boot time by caching expensive operations.
diff --git a/test/environments/railsedge/config/environment.rb b/test/environments/railsedge/config/environment.rb
index c2744831ac..d0c0782949 100644
--- a/test/environments/railsedge/config/environment.rb
+++ b/test/environments/railsedge/config/environment.rb
@@ -3,7 +3,7 @@
# frozen_string_literal: true
# Load the Rails application.
-require_relative "application"
+require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
diff --git a/test/environments/railsedge/config/initializers/test.rb b/test/environments/railsedge/config/initializers/test.rb
index 1d88e77b0a..9981aac1a3 100644
--- a/test/environments/railsedge/config/initializers/test.rb
+++ b/test/environments/railsedge/config/initializers/test.rb
@@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base
include ::NewRelic::Agent::MethodTracer
def sniff
- puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \
+ puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \
"air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \
- "scent receptors. " \
- "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/"
+ 'scent receptors. ' \
+ 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/'
end
add_method_tracer :sniff
diff --git a/test/helpers/file_searching.rb b/test/helpers/file_searching.rb
index 999046bdb5..3e97344b30 100644
--- a/test/helpers/file_searching.rb
+++ b/test/helpers/file_searching.rb
@@ -6,22 +6,22 @@ module NewRelic
module TestHelpers
module FileSearching
def all_rb_files
- pattern = File.expand_path(gem_root + "/**/*.{rb,rhtml}")
+ pattern = File.expand_path(gem_root + '/**/*.{rb,rhtml}')
Dir[pattern]
end
def all_rb_and_js_files
- pattern = File.expand_path(gem_root + "/**/*.{rb,js}")
+ pattern = File.expand_path(gem_root + '/**/*.{rb,js}')
Dir[pattern]
end
def all_files
- pattern = File.expand_path(gem_root + "/**/*")
+ pattern = File.expand_path(gem_root + '/**/*')
Dir[pattern]
end
def gem_root
- File.expand_path(File.dirname(__FILE__) + "/../../")
+ File.expand_path(File.dirname(__FILE__) + '/../../')
end
end
end
diff --git a/test/helpers/misc.rb b/test/helpers/misc.rb
index 924e483174..00d6493967 100644
--- a/test/helpers/misc.rb
+++ b/test/helpers/misc.rb
@@ -30,7 +30,7 @@ def default_service(stubbed_method_overrides = {})
def fixture_tcp_socket(response)
# Don't actually talk to Google.
- socket = stub("socket").tap do |s|
+ socket = stub('socket').tap do |s|
s.stubs(:closed?).returns(false)
s.stubs(:close)
s.stubs(:setsockopt)
@@ -48,7 +48,7 @@ def fixture_tcp_socket(response)
stubs(:check_write) { self.write_checker = Proc.new }
stubs(:write) do |buf|
- self.write_checker.call(buf) if self.write_checker
+ self.write_checker&.call(buf)
buf.length
end
diff --git a/test/helpers/mongo_metric_builder.rb b/test/helpers/mongo_metric_builder.rb
index 4493e36dce..8f2a8beea0 100644
--- a/test/helpers/mongo_metric_builder.rb
+++ b/test/helpers/mongo_metric_builder.rb
@@ -17,7 +17,7 @@ def build_test_metrics(name, instance_metrics = false)
end
NewRelic::Agent::Datastores::MetricHelper.metrics_for(
- "MongoDB", name, @collection_name, host, port
+ 'MongoDB', name, @collection_name, host, port
)
end
diff --git a/test/helpers/transaction_sample.rb b/test/helpers/transaction_sample.rb
index 0a28bb64c9..7cfbe97ed7 100644
--- a/test/helpers/transaction_sample.rb
+++ b/test/helpers/transaction_sample.rb
@@ -11,12 +11,12 @@ def make_sql_transaction(*sql)
in_transaction('/path') do
sampler = NewRelic::Agent.instance.transaction_sampler
- sampler.notice_push_frame(state, "a")
+ sampler.notice_push_frame(state, 'a')
explainer = NewRelic::Agent::Instrumentation::ActiveRecord::EXPLAINER
- sql.each { |sql_statement| sampler.notice_sql(sql_statement, {:adapter => "mysql"}, 0, state, explainer) }
+ sql.each { |sql_statement| sampler.notice_sql(sql_statement, {:adapter => 'mysql'}, 0, state, explainer) }
sleep(0.02)
yield if block_given?
- sampler.notice_pop_frame(state, "a")
+ sampler.notice_pop_frame(state, 'a')
end
return sampler.last_sample
diff --git a/test/minitest/test_time_reporter.rb b/test/minitest/test_time_reporter.rb
index 79c18c26e3..9523341f70 100644
--- a/test/minitest/test_time_reporter.rb
+++ b/test/minitest/test_time_reporter.rb
@@ -57,7 +57,7 @@ def ten_slowest_tests
end
def output_report
- return unless ENV["VERBOSE_TEST_OUTPUT"]
+ return unless ENV['VERBOSE_TEST_OUTPUT']
puts "\n====== Ten slowest tests ======\n"
ten_slowest_tests.each_with_index do |element, index|
diff --git a/test/multiverse/lib/multiverse.rb b/test/multiverse/lib/multiverse.rb
index 8c3512408b..c1bfd8ba3f 100644
--- a/test/multiverse/lib/multiverse.rb
+++ b/test/multiverse/lib/multiverse.rb
@@ -35,3 +35,4 @@ module Multiverse
require 'multiverse/runner'
require 'multiverse/envfile'
require 'multiverse/suite'
+require 'multiverse/gem_manifest'
diff --git a/test/multiverse/lib/multiverse/color.rb b/test/multiverse/lib/multiverse/color.rb
index 62705c4ed6..c3fd940848 100644
--- a/test/multiverse/lib/multiverse/color.rb
+++ b/test/multiverse/lib/multiverse/color.rb
@@ -9,15 +9,15 @@ def colorize(color_code, content)
end
def red(string)
- colorize("0;31;49", string)
+ colorize('0;31;49', string)
end
def green(string)
- colorize("0;32;49", string)
+ colorize('0;32;49', string)
end
def yellow(string)
- colorize("0;33;49", string)
+ colorize('0;33;49', string)
end
end
end
diff --git a/test/multiverse/lib/multiverse/envfile.rb b/test/multiverse/lib/multiverse/envfile.rb
index b0aa9c3e01..2c5fb4a53e 100644
--- a/test/multiverse/lib/multiverse/envfile.rb
+++ b/test/multiverse/lib/multiverse/envfile.rb
@@ -10,11 +10,12 @@ class Envfile
attr_reader :before, :after, :mode, :skip_message, :omit_collector
attr_reader :instrumentation_permutations
- def initialize(file_path)
+ def initialize(file_path, options = {})
self.file_path = file_path
- @instrumentation_permutations = ["chain"]
+ @instrumentation_permutations = ['chain']
@gemfiles = []
@mode = 'fork'
+ @ignore_ruby_version = options[:ignore_ruby_version] if options.key?(:ignore_ruby_version)
if File.exist?(file_path)
@text = File.read(self.file_path)
instance_eval(@text)
@@ -37,7 +38,7 @@ def create_gemfiles(versions)
)
end
- version = if version && version.start_with?('=')
+ version = if version&.start_with?('=')
add_version(version.sub('= ', ''), false) # don't twiddle wakka
else
add_version(version)
@@ -48,6 +49,8 @@ def create_gemfiles(versions)
end
def unsupported_ruby_version?(last_supported_ruby_version, first_supported_ruby_version)
+ return false if @ignore_ruby_version
+
last_supported_ruby_version?(last_supported_ruby_version) ||
first_supported_ruby_version?(first_supported_ruby_version)
end
@@ -62,7 +65,7 @@ def gemfile(content)
end
def ruby3_gem_sorted_set
- RUBY_VERSION >= "3.0.0" ? "gem 'sorted_set'" : ""
+ RUBY_VERSION >= '3.0.0' ? "gem 'sorted_set'" : ''
end
def omit_collector!
@@ -99,6 +102,10 @@ def [](key)
@gemfiles[key]
end
+ def to_ary
+ @gemfiles
+ end
+
def permutations
@instrumentation_permutations.size
end
diff --git a/test/multiverse/lib/multiverse/gem_manifest.rb b/test/multiverse/lib/multiverse/gem_manifest.rb
new file mode 100755
index 0000000000..d8e8b2d708
--- /dev/null
+++ b/test/multiverse/lib/multiverse/gem_manifest.rb
@@ -0,0 +1,120 @@
+#!/usr/bin/env ruby
+# This file is distributed under New Relic's license terms.
+# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
+# frozen_string_literal: true
+
+require 'fileutils'
+require 'json'
+require 'tmpdir'
+
+module Multiverse
+ class GemManifest
+ GEMFILE_HEADER = %q(source 'https://rubygems.org')
+ LOCKFILE = 'Gemfile.lock'
+ OUTPUT_FILE = "gem_manifest_#{RUBY_VERSION}.json"
+ SUITES_DIR = File.expand_path('../../../suites', __FILE__)
+
+ def initialize(args = [])
+ @suite_paths = []
+ @gems = {}
+ @opwd = Dir.pwd
+ discover_suites
+ end
+
+ def report
+ process_suites
+ determine_latest_versions
+ deliver_output
+ end
+
+ private
+
+ def create_lockfile(dir)
+ Bundler.with_unbundled_env do
+ `cd #{dir} && bundle lock --lockfile=#{File.join(dir, LOCKFILE)}`
+ end
+ end
+
+ def deliver_output
+ results = @gems.each_with_object({}) do |(name, versions), hash|
+ hash[name] = versions.keys
+ puts "#{name} => #{hash[name]}"
+ end
+ FileUtils.rm_f(OUTPUT_FILE)
+ File.open(OUTPUT_FILE, 'w') { |f| f.print results.to_json }
+ puts
+ puts "Results written to #{OUTPUT_FILE}"
+ end
+
+ def determine_latest_versions
+ gems_wanting_latest = @gems.select { |_name, versions| versions.key?(nil) }.keys
+ gemfile_body = gems_wanting_latest.map { |name| "gem '#{name}'" }.join("\n")
+ dir = Dir.mktmpdir
+ File.open(File.join(dir, 'Gemfile'), 'w') do |f|
+ f.puts GEMFILE_HEADER
+ f.puts gemfile_body
+ end
+ create_lockfile(dir)
+ parse_lockfile(dir)
+ end
+
+ def discover_suites
+ Dir.glob(File.join(SUITES_DIR, '*')).each do |path|
+ @suite_paths << path if File.directory?(path)
+ end
+ end
+
+ def gems_from_gemfile_body(body, path)
+ body.split("\n").each do |line|
+ next if line.empty? || line.match?(/(?:^\s*(?:#|if|else|end))|newrelic_(?:rpm|prepender)/)
+
+ if line =~ /.*gem\s+['"]([^'"]+)['"](?:,\s+['"]([^'"]+)['"])?/
+ gem = Regexp.last_match(1)
+ version = Regexp.last_match(2)
+ @gems[gem] ||= {}
+ @gems[gem][version] = 1
+ else
+ raise "Couldn't figure out how to parse lines from evaluating the Envfile file at #{path}!"
+ end
+ end
+ end
+
+ def parse_lockfile(dir)
+ content = File.read(File.join(dir, LOCKFILE))
+ gem_specs = Regexp.last_match(1) if content =~ /\AGEM\n.*\n\s+specs:\n(.*?)\n\n/m
+ desired_indentation = nil
+ hash = gem_specs.split("\n").each_with_object({}) do |line, h|
+ indentation = Regexp.last_match(1) if line =~ /^(\s+)/
+ desired_indentation ||= indentation
+ next unless indentation == desired_indentation
+
+ h[Regexp.last_match(1).strip] = Regexp.last_match(2).strip if line =~ /^(.*?)\s+\((.*?)\)/
+ end
+ process_lockfile_hash(hash)
+ end
+
+ def process_lockfile_hash(hash)
+ hash.each do |gem, version|
+ next unless @gems.key?(gem)
+
+ @gems[gem].delete(nil)
+ @gems[gem]["latest (#{version})"] = 1
+ end
+ end
+
+ def process_suites
+ @suite_paths.each do |path|
+ Dir.chdir(path) # needed for Envfile.new's instance_eval call
+ Multiverse::Envfile.new(File.join(path, 'Envfile'), ignore_ruby_version: true).map do |body|
+ gems_from_gemfile_body(body, path)
+ end
+ end
+ ensure
+ Dir.chdir(@opwd)
+ end
+
+ def verify_mode
+ raise "Invalid mode '#{@mode}' - must be one of #{MODES}" unless MODES.include?(@mode)
+ end
+ end
+end
diff --git a/test/multiverse/lib/multiverse/output_collector.rb b/test/multiverse/lib/multiverse/output_collector.rb
index debe99d4f6..b12fcece65 100644
--- a/test/multiverse/lib/multiverse/output_collector.rb
+++ b/test/multiverse/lib/multiverse/output_collector.rb
@@ -26,7 +26,7 @@ def self.buffer(suite, env)
key = [suite, env]
@buffer_lock.synchronize do
@buffers ||= {}
- @buffers[key] ||= String.new('')
+ @buffers[key] ||= +''
@buffers[key]
end
end
@@ -50,7 +50,7 @@ def self.suite_report(suite, env)
def self.overall_report
output('', '')
if failing_output.empty?
- output(green("There were no test failures"))
+ output(green('There were no test failures'))
else
to_output = failing_output_header + failing_output + failing_output_footer
output(*to_output)
@@ -60,27 +60,27 @@ def self.overall_report
end
def self.failing_output_header
- [red("*" * 80),
- red("Repeating failed test output"),
- red("*" * 80),
- ""]
+ [red('*' * 80),
+ red('Repeating failed test output'),
+ red('*' * 80),
+ '']
end
def self.failing_output_footer
- ["",
- red("*" * 80),
+ ['',
+ red('*' * 80),
red("There were failures in #{failing_output.size} test suites"),
- "",
+ '',
@failing_suites.map { |suite, env| red("#{suite} failed in env #{env}") },
- red("*" * 80)]
+ red('*' * 80)]
end
# Saves the failing out put to the working directory of the container
# where it is later read and output as annotations of the github workflow
def self.save_output_to_error_file(lines)
@output_lock.synchronize do
- filepath = ENV["GITHUB_WORKSPACE"] || File.expand_path(File.dirname(__FILE__))
- output_file = File.join(filepath, "errors.txt")
+ filepath = ENV['GITHUB_WORKSPACE'] || File.expand_path(File.dirname(__FILE__))
+ output_file = File.join(filepath, 'errors.txt')
existing_lines = []
if File.exist?(output_file)
@@ -90,7 +90,7 @@ def self.save_output_to_error_file(lines)
lines = lines.split("\n") if lines.is_a?(String)
File.open(output_file, 'w') do |f|
f.puts existing_lines
- f.puts "*" * 80
+ f.puts '*' * 80
f.puts lines
end
end
diff --git a/test/multiverse/lib/multiverse/runner.rb b/test/multiverse/lib/multiverse/runner.rb
index 0a89a94560..d67b079c86 100644
--- a/test/multiverse/lib/multiverse/runner.rb
+++ b/test/multiverse/lib/multiverse/runner.rb
@@ -33,12 +33,12 @@ def notice_exit_status(i)
def parse_args(args)
opts = {}
args.each do |(k, v)|
- if v.index("name=") == 0
- parts = v.split("=")
+ if v.index('name=') == 0
+ parts = v.split('=')
opts[:names] ||= []
opts[:names] << parts.last
- elsif v.include?("=")
- parts = v.split("=")
+ elsif v.include?('=')
+ parts = v.split('=')
opts[parts.first.to_sym] = parts.last
elsif k != :suite
opts[v.to_sym] = true
@@ -47,7 +47,7 @@ def parse_args(args)
opts
end
- def run(filter = "", opts = {})
+ def run(filter = '', opts = {})
# This file is generated by TestTimeReporter.
# TestTimeReporter cannot be loaded until minitest has been loaded by an
# individual suite, so we cannot define this inside the TestTimeReporter
@@ -59,7 +59,7 @@ def run(filter = "", opts = {})
puts yellow(suite.execution_message)
suite.each_instrumentation_method do |method|
if opts.key?(:method) && method != opts[:method] && suite.instrumentation_permutations.length > 1
- puts "Skipping method '#{method}' while focusing only on '#{opts[:method]}'" if ENV["VERBOSE_TEST_OUTPUT"]
+ puts "Skipping method '#{method}' while focusing only on '#{opts[:method]}'" if ENV['VERBOSE_TEST_OUTPUT']
next
end
suite.execute(method)
@@ -67,7 +67,7 @@ def run(filter = "", opts = {})
end
end
- def prime(filter = "", opts = {})
+ def prime(filter = '', opts = {})
execute_suites(filter, opts) do |suite|
suite.prime
end
@@ -79,7 +79,7 @@ def execute_suites(filter, opts)
next if dir.start_with?('.')
next unless passes_filter?(dir, filter)
- next unless File.exist?(File.join(full_path, "Envfile"))
+ next unless File.exist?(File.join(full_path, 'Envfile'))
begin
suite = Suite.new(full_path, opts)
@@ -98,20 +98,20 @@ def execute_suites(filter, opts)
end
GROUPS = {
- "agent" => %w[agent_only bare config_file_loading deferred_instrumentation high_security no_json json marshalling thread yajl],
- "background" => %w[delayed_job sidekiq resque],
- "background_2" => ["rake"],
- "database" => %w[elasticsearch mongo redis sequel],
- "rails" => %w[active_record active_record_pg rails rails_prepend activemerchant],
- "frameworks" => %w[sinatra padrino grape],
- "httpclients" => %w[curb excon httpclient],
- "httpclients_2" => %w[typhoeus net_http httprb],
- "infinite_tracing" => ["infinite_tracing"],
-
- "rest" => [] # Specially handled below
+ 'agent' => %w[agent_only bare config_file_loading deferred_instrumentation high_security no_json json marshalling thread yajl],
+ 'background' => %w[delayed_job sidekiq resque],
+ 'background_2' => ['rake'],
+ 'database' => %w[elasticsearch mongo redis sequel],
+ 'rails' => %w[active_record active_record_pg rails rails_prepend activemerchant],
+ 'frameworks' => %w[sinatra padrino grape],
+ 'httpclients' => %w[curb excon httpclient],
+ 'httpclients_2' => %w[typhoeus net_http httprb],
+ 'infinite_tracing' => ['infinite_tracing'],
+
+ 'rest' => [] # Specially handled below
}
- if RUBY_PLATFORM == "java"
+ if RUBY_PLATFORM == 'java'
GROUPS['agent'].delete('agent_only')
end
@@ -122,7 +122,7 @@ def execute_suites(filter, opts)
end
def excluded?(suite)
- return true if suite == 'agent_only' and RUBY_PLATFORM == "java"
+ return true if suite == 'agent_only' and RUBY_PLATFORM == 'java'
return true if suite == 'active_record' and RUBY_VERSION >= '3.0.0'
end
@@ -131,8 +131,8 @@ def passes_filter?(dir, filter)
return false if excluded?(dir)
- if filter.include?("group=")
- keys = filter.sub("group=", "").split(';') # supports multiple groups passed in ";" delimited
+ if filter.include?('group=')
+ keys = filter.sub('group=', '').split(';') # supports multiple groups passed in ";" delimited
combined_groups = []
# grabs all the suites that are in each of the groups passed in
@@ -151,7 +151,7 @@ def passes_filter?(dir, filter)
# the "rest" group is one of the groups being passed in AND the directory is not in any other group
# OR
# the directory is one of the suites included in one of the non-rest groups passed in
- (keys.include?("rest") && !GROUPS.values.flatten.include?(dir)) || (combined_groups.any? && combined_groups.include?(dir))
+ (keys.include?('rest') && !GROUPS.values.flatten.include?(dir)) || (combined_groups.any? && combined_groups.include?(dir))
else
dir.eql?(filter)
end
diff --git a/test/multiverse/lib/multiverse/suite.rb b/test/multiverse/lib/multiverse/suite.rb
index 87df88e182..8864aeadb5 100755
--- a/test/multiverse/lib/multiverse/suite.rb
+++ b/test/multiverse/lib/multiverse/suite.rb
@@ -29,7 +29,7 @@ class Suite
def initialize(directory, opts = {})
self.directory = File.expand_path(directory)
self.opts = opts
- ENV["VERBOSE"] = '1' if opts[:verbose]
+ ENV['VERBOSE'] = '1' if opts[:verbose]
end
def self.encode_options(decoded_opts)
@@ -45,7 +45,7 @@ def suite
end
def seed
- opts.fetch(:seed, "")
+ opts.fetch(:seed, '')
end
def debug
@@ -100,7 +100,7 @@ def environments
# load the environment for this suite after we've forked
def load_dependencies(gemfile_text, env_index, should_print = true)
- ENV["BUNDLE_GEMFILE"] = "Gemfile.#{env_index}"
+ ENV['BUNDLE_GEMFILE'] = "Gemfile.#{env_index}"
clean_gemfiles(env_index)
begin
generate_gemfile(gemfile_text, env_index)
@@ -109,7 +109,7 @@ def load_dependencies(gemfile_text, env_index, should_print = true)
if verbose?
puts "#{e.class}: #{e}"
puts e.backtrace
- puts "Fast local bundle failed. Attempting to install from rubygems.org"
+ puts 'Fast local bundle failed. Attempting to install from rubygems.org'
end
clean_gemfiles(env_index)
generate_gemfile(gemfile_text, env_index, false)
@@ -127,7 +127,7 @@ def with_potentially_mismatched_bundler
puts "Encountered Bundler error: #{error.message}"
puts "Currently Active Bundler Version: #{::Bundler::VERSION}"
end
- change_lock_version(`pwd`, ENV["BUNDLE_GEMFILE"])
+ change_lock_version(`pwd`, ENV['BUNDLE_GEMFILE'])
@retried = true
retry
end
@@ -146,20 +146,20 @@ def bundler_cache_dir
# Ensures we bundle will recognize an explicit version number on command line
def safe_explicit(version)
- return version if version.to_s == ""
+ return version if version.to_s == ''
test_version = `bundle #{version} --version`.include?('Could not find command')
- test_version ? "" : version
+ test_version ? '' : version
end
def explicit_bundler_version(dir)
- fn = File.join(dir, ".bundler-version")
+ fn = File.join(dir, '.bundler-version')
version = File.exist?(fn) ? File.read(fn).chomp.to_s.strip : nil
- safe_explicit(version.to_s == "" ? nil : "_#{version}_")
+ safe_explicit(version.to_s == '' ? nil : "_#{version}_")
end
def bundle_show_env(bundle_cmd)
- return unless ENV["BUNDLE_SHOW_ENV"]
+ return unless ENV['BUNDLE_SHOW_ENV']
puts `#{bundle_cmd} env`
end
@@ -176,13 +176,13 @@ def bundle_install(dir)
full_bundle_cmd = "#{bundle_cmd} install"
result = ShellUtils.try_command_n_times(full_bundle_cmd, 3)
unless $?.success?
- puts "Failed local bundle, trying again without the version lock..."
- change_lock_version(dir, ENV["BUNDLE_GEMFILE"])
+ puts 'Failed local bundle, trying again without the version lock...'
+ change_lock_version(dir, ENV['BUNDLE_GEMFILE'])
result = ShellUtils.try_command_n_times(full_bundle_cmd, 3)
end
result = red(result) unless $?.success?
- puts result if ENV["VERBOSE_TEST_OUTPUT"]
+ puts result if ENV['VERBOSE_TEST_OUTPUT']
$?
end
@@ -267,7 +267,7 @@ def ensure_bundle_uncached(env_index)
end
def ruby3_gem_webrick
- RUBY_VERSION >= "3.0.0" ? "gem 'webrick'" : ""
+ RUBY_VERSION >= '3.0.0' ? "gem 'webrick'" : ''
end
def generate_gemfile(gemfile_text, env_index, local = true)
@@ -275,8 +275,8 @@ def generate_gemfile(gemfile_text, env_index, local = true)
File.open(gemfile, 'w') do |f|
f.puts 'source "https://rubygems.org"'
f.print gemfile_text
- f.puts newrelic_gemfile_line unless gemfile_text =~ /^\s*gem .newrelic_rpm./
- f.puts minitest_line unless gemfile_text =~ /^\s*gem .minitest[^_]./
+ f.puts newrelic_gemfile_line unless /^\s*gem .newrelic_rpm./.match?(gemfile_text)
+ f.puts minitest_line unless /^\s*gem .minitest[^_]./.match?(gemfile_text)
f.puts "gem 'rake'" unless gemfile_text =~ /^\s*gem .rake[^_]./ || suite == 'rake'
f.puts "gem 'rackup'" if need_rackup?(gemfile_text)
@@ -348,7 +348,7 @@ def require_minitest
end
def print_environment
- puts yellow("Environment loaded with:") if verbose?
+ puts yellow('Environment loaded with:') if verbose?
gems = with_potentially_mismatched_bundler do
::Bundler.definition.specs.inject([]) do |m, s|
next m if s.name == 'bundler'
@@ -383,17 +383,17 @@ def print_environment
# continuous integration server. We do this by passing -Xverify:none to
# the JVM.
def optimize_jruby_startups
- return unless RUBY_PLATFORM == "java"
+ return unless RUBY_PLATFORM == 'java'
- ENV["JRUBY_OPTS"] = "--dev"
+ ENV['JRUBY_OPTS'] = '--dev'
end
def execute_child_environment(env_index, instrumentation_method)
with_unbundled_env do
configure_instrumentation_method(instrumentation_method)
optimize_jruby_startups
- ENV["MULTIVERSE_ENV"] = env_index.to_s
- ENV["MULTIVERSE_INSTRUMENTATION_METHOD"] = instrumentation_method
+ ENV['MULTIVERSE_ENV'] = env_index.to_s
+ ENV['MULTIVERSE_INSTRUMENTATION_METHOD'] = instrumentation_method
log_test_running_process
configure_before_bundling
@@ -427,7 +427,7 @@ def check_environment_condition
end
def prime
- ENV["VERBOSE"] = "1"
+ ENV['VERBOSE'] = '1'
return unless check_environment_condition
puts yellow("\nPriming #{directory.inspect}")
@@ -462,17 +462,17 @@ def execute(instrumentation_method)
configure_instrumentation_method(instrumentation_method)
- environments.before.call if environments.before
+ environments.before&.call
if should_serialize?
execute_serial(instrumentation_method)
else
execute_parallel(instrumentation_method)
end
- environments.after.call if environments.after
+ environments.after&.call
rescue => e
puts e.backtrace
puts red("Failure during execution of suite #{directory.inspect}.")
- puts red("This typically is a result of a Ruby failure in your Envfile.")
+ puts red('This typically is a result of a Ruby failure in your Envfile.')
puts
puts red(e.class)
puts red(e.message)
@@ -567,17 +567,17 @@ def trigger_test_run
# Autorun behaves differently across the different Ruby version we have
# to support, so this is simplest for making our test running consistent
options = []
- options << "-v" if verbose?
- options << "--seed=#{seed}" unless seed == ""
- options << "--name=/#{names.map { |n| n + ".*" }.join("|")}/" unless names == []
+ options << '-v' if verbose?
+ options << "--seed=#{seed}" unless seed == ''
+ options << "--name=/#{names.map { |n| n + '.*' }.join('|')}/" unless names == []
original_options = options.dup
# MiniTest 5.0 moved things around, so choose which way to run it
if ::MiniTest.respond_to?(:run)
- test_run = ::MiniTest.run(options)
+ passed = ::MiniTest.run(options)
else
- test_run = ::MiniTest::Unit.new.run(options)
+ passed = ::MiniTest::Unit.new.run(options)
end
load(@after_file) if @after_file
@@ -593,13 +593,9 @@ def trigger_test_run
end
end
- if test_run
- exit(test_run)
- else
- puts "No tests found with those options."
- puts "options: #{original_options}"
- exit(1)
- end
+ puts 'One or more failures or errors were seen!' unless passed
+ puts "Options used: #{original_options}"
+ exit(passed) # `exit true` returns 0, `exit false` returns 1
end
def configure_before_bundling
@@ -652,15 +648,15 @@ def disable_harvest_thread
# destabilizing if it's running. Also, multiple restarts result in lots of
# threads running in some test suites.
- ENV["NEWRELIC_DISABLE_HARVEST_THREAD"] = "true"
+ ENV['NEWRELIC_DISABLE_HARVEST_THREAD'] = 'true'
end
def configure_fake_collector
- ENV["NEWRELIC_OMIT_FAKE_COLLECTOR"] = "true" if environments.omit_collector
+ ENV['NEWRELIC_OMIT_FAKE_COLLECTOR'] = 'true' if environments.omit_collector
end
def configure_instrumentation_method(method)
- ENV["MULTIVERSE_INSTRUMENTATION_METHOD"] = $instrumentation_method = method
+ ENV['MULTIVERSE_INSTRUMENTATION_METHOD'] = $instrumentation_method = method
end
def require_helpers
@@ -677,15 +673,15 @@ def execute_ruby_files
next if exclude?(file)
ENV['FILTER_FILE'] = filter_file if filter_file && infinite_tracing_suite?
- require "./" + File.basename(file, ".rb")
+ require './' + File.basename(file, '.rb')
end
end
def ordered_ruby_files(directory)
files = Dir[File.join(directory, '*.rb')]
- @before_file = files.find { |file| File.basename(file) == "before_suite.rb" }
- @after_file = files.find { |file| File.basename(file) == "after_suite.rb" }
+ @before_file = files.find { |file| File.basename(file) == 'before_suite.rb' }
+ @after_file = files.find { |file| File.basename(file) == 'after_suite.rb' }
files.delete(@before_file)
files.delete(@after_file)
@@ -702,7 +698,7 @@ def ordered_ruby_files(directory)
end
def verbose?
- ENV['VERBOSE'] == "1" || ENV['VERBOSE'] == "true"
+ ENV['VERBOSE'] == '1' || ENV['VERBOSE'] == 'true'
end
# Sidekiq v4.2.0 and later will bail out at startup if we try to
diff --git a/test/multiverse/lib/multiverse/time_report_output.rb b/test/multiverse/lib/multiverse/time_report_output.rb
index 3d7502845e..9127caa66d 100644
--- a/test/multiverse/lib/multiverse/time_report_output.rb
+++ b/test/multiverse/lib/multiverse/time_report_output.rb
@@ -9,7 +9,7 @@ def sort_and_print_test_times
test_times = hash_values_to_float(test_times)
print_top_ten(sort_ten_slowest_tests(test_times))
else
- puts yellow('Test timing data not found.') if ENV["VERBOSE_TEST_OUTPUT"]
+ puts yellow('Test timing data not found.') if ENV['VERBOSE_TEST_OUTPUT']
end
end
@@ -27,7 +27,7 @@ def hash_values_to_float(original_hash)
end
def print_top_ten(top_ten)
- return unless ENV["VERBOSE_TEST_OUTPUT"]
+ return unless ENV['VERBOSE_TEST_OUTPUT']
puts "\n====== Ten slowest tests ======\n"
top_ten.each_with_index do |element, index|
diff --git a/test/multiverse/suites/active_record/Rakefile b/test/multiverse/suites/active_record/Rakefile
index 897a142a8d..92eeebd24e 100644
--- a/test/multiverse/suites/active_record/Rakefile
+++ b/test/multiverse/suites/active_record/Rakefile
@@ -4,7 +4,7 @@
require_relative 'config/database'
-desc "Setup for ActiveRecord"
+desc 'Setup for ActiveRecord'
task :environment do
if defined?(DatabaseTasks)
ActiveRecord::Base.configurations = DatabaseTasks.database_configuration
diff --git a/test/multiverse/suites/active_record/active_record_test.rb b/test/multiverse/suites/active_record/active_record_test.rb
index 7d5818d29d..4fc0f0e1b9 100644
--- a/test/multiverse/suites/active_record/active_record_test.rb
+++ b/test/multiverse/suites/active_record/active_record_test.rb
@@ -29,7 +29,7 @@ def active_record_version
if defined?(::ActiveRecord::VERSION::MINOR)
Gem::Version.new(::ActiveRecord::VERSION::STRING)
else
- Gem::Version.new("2.1.0") # Can't tell between 2.1 and 2.2. Meh.
+ Gem::Version.new('2.1.0') # Can't tell between 2.1 and 2.2. Meh.
end
end
end
@@ -159,7 +159,7 @@ def test_metrics_for_find_via_named_scope
def test_metrics_for_exists
in_web_transaction do
- Order.exists?(["name=?", "jeff"])
+ Order.exists?(['name=?', 'jeff'])
end
if active_record_major_version == 3 && [0, 1].include?(active_record_minor_version)
@@ -201,7 +201,7 @@ def test_metrics_for_delete_all
def test_metrics_for_relation_delete
in_web_transaction do
- order = Order.create(:name => "lava")
+ order = Order.create(:name => 'lava')
Order.delete(order.id)
end
@@ -216,7 +216,7 @@ def test_metrics_for_relation_delete
if active_record_version >= Gem::Version.new('3.0.0')
def test_metrics_for_delete
in_web_transaction do
- order = Order.create("name" => "burt")
+ order = Order.create('name' => 'burt')
order.delete
end
@@ -225,7 +225,7 @@ def test_metrics_for_delete
def test_metrics_for_touch
in_web_transaction do
- order = Order.create("name" => "wendy")
+ order = Order.create('name' => 'wendy')
order.touch
end
@@ -353,7 +353,7 @@ def test_destroy_via_dependent_destroy
if active_record_version >= Gem::Version.new('4.0.0')
def test_metrics_for_update
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.update(:name => 'walter')
end
@@ -362,7 +362,7 @@ def test_metrics_for_update
def test_metrics_for_update_bang
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.update!(:name => 'walter')
end
@@ -372,7 +372,7 @@ def test_metrics_for_update_bang
def test_metrics_for_update_attribute
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.update_attribute(:name, 'walter')
end
@@ -381,7 +381,7 @@ def test_metrics_for_update_attribute
def test_metrics_for_save
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.name = 'walter'
order.save
end
@@ -391,7 +391,7 @@ def test_metrics_for_save
def test_metrics_for_save_bang
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.name = 'walter'
order.save!
end
@@ -401,18 +401,18 @@ def test_metrics_for_save_bang
def test_nested_metrics_dont_get_model_name
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.name = 'walter'
order.save!
end
- assert_metrics_recorded(["Datastore/operation/Memcached/get"])
+ assert_metrics_recorded(['Datastore/operation/Memcached/get'])
refute_metrics_match(/Memcached.*Order/)
end
def test_metrics_for_destroy
in_web_transaction do
- order = Order.create("name" => "burt")
+ order = Order.create('name' => 'burt')
order.destroy
end
@@ -431,8 +431,8 @@ def test_metrics_for_direct_sql_select
def test_metrics_for_direct_sql_other
in_web_transaction do
conn = Order.connection
- conn.execute("begin")
- conn.execute("commit")
+ conn.execute('begin')
+ conn.execute('commit')
end
assert_generic_rollup_metrics('other')
@@ -442,7 +442,7 @@ def test_metrics_for_direct_sql_show
if supports_show_tables?
in_web_transaction do
conn = Order.connection
- conn.execute("show tables")
+ conn.execute('show tables')
end
assert_generic_rollup_metrics('show')
@@ -453,7 +453,7 @@ def test_still_records_metrics_in_error_cases
# Let's trigger an active record SQL StatementInvalid error
assert_raises ::ActiveRecord::StatementInvalid do
in_web_transaction do
- Order.connection.select_rows("select * from askdjfhkajsdhflkjh")
+ Order.connection.select_rows('select * from askdjfhkajsdhflkjh')
end
end
@@ -480,8 +480,8 @@ def test_only_supportability_metrics_recorded_with_disable_all_tracing
refute last_transaction_trace
assert_metrics_recorded_exclusive([
- "Supportability/API/disable_all_tracing",
- "Supportability/API/drop_buffered_data"
+ 'Supportability/API/disable_all_tracing',
+ 'Supportability/API/drop_buffered_data'
])
end
@@ -585,7 +585,7 @@ def test_cached_calls_are_not_recorded_with_select_all
def test_with_database_metric_name
in_web_transaction do
- Order.create(:name => "eely")
+ Order.create(:name => 'eely')
NewRelic::Agent.with_database_metric_name('Eel', 'squirm') do
Order.connection.select_rows("SELECT id FROM #{Order.table_name}")
end
@@ -636,16 +636,16 @@ def assert_activerecord_metrics(model, operation, stats = {})
assert_metrics_recorded({
"Datastore/statement/#{current_product}/#{model}/#{operation}" => stats,
"Datastore/operation/#{current_product}/#{operation}" => {},
- "Datastore/allWeb" => {},
- "Datastore/all" => {}
+ 'Datastore/allWeb' => {},
+ 'Datastore/all' => {}
})
end
def assert_generic_rollup_metrics(operation)
assert_metrics_recorded([
"Datastore/operation/#{current_product}/#{operation}",
- "Datastore/allWeb",
- "Datastore/all"
+ 'Datastore/allWeb',
+ 'Datastore/all'
])
end
end
diff --git a/test/multiverse/suites/active_record/app/models/models.rb b/test/multiverse/suites/active_record/app/models/models.rb
index 5a104a6f79..75236a79e8 100644
--- a/test/multiverse/suites/active_record/app/models/models.rb
+++ b/test/multiverse/suites/active_record/app/models/models.rb
@@ -23,7 +23,7 @@ class Order < ActiveRecord::Base
validate :touches_another_datastore
def touches_another_datastore
- NewRelic::Agent::Datastores.wrap("Memcached", "get") do
+ NewRelic::Agent::Datastores.wrap('Memcached', 'get') do
# Fake hitting a cache during validation
end
end
diff --git a/test/multiverse/suites/active_record/ar_method_aliasing.rb b/test/multiverse/suites/active_record/ar_method_aliasing.rb
index 0b229dc15a..03825b084b 100644
--- a/test/multiverse/suites/active_record/ar_method_aliasing.rb
+++ b/test/multiverse/suites/active_record/ar_method_aliasing.rb
@@ -15,7 +15,7 @@ class InstrumentActiveRecordMethods < Minitest::Test
setup_and_teardown_agent
def test_basic_creation
- a_user = User.new(:name => "Bob")
+ a_user = User.new(:name => 'Bob')
assert_predicate a_user, :new_record?
a_user.save!
@@ -25,14 +25,14 @@ def test_basic_creation
end
def test_alias_collection_query_method
- a_user = User.new(:name => "Bob")
+ a_user = User.new(:name => 'Bob')
a_user.save!
a_user = User.first
assert_predicate User, :connected?
- an_alias = Alias.new(:user_id => a_user.id, :aka => "the Blob")
+ an_alias = Alias.new(:user_id => a_user.id, :aka => 'the Blob')
assert_predicate an_alias, :new_record?
an_alias.save!
diff --git a/test/multiverse/suites/active_record/before_suite.rb b/test/multiverse/suites/active_record/before_suite.rb
index c83d2fc714..46cd044e77 100644
--- a/test/multiverse/suites/active_record/before_suite.rb
+++ b/test/multiverse/suites/active_record/before_suite.rb
@@ -4,7 +4,7 @@
def redefine_mysql_primary_key(const_str)
const = Object.const_get(const_str) rescue return
- const[:primary_key] = "int(11) auto_increment PRIMARY KEY"
+ const[:primary_key] = 'int(11) auto_increment PRIMARY KEY'
end
# MySql 5.7 and later no longer support NULL in primary keys
@@ -14,8 +14,8 @@ def redefine_mysql_primary_key(const_str)
require 'active_record'
require 'active_record/connection_adapters/mysql2_adapter'
- redefine_mysql_primary_key "::ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::NATIVE_DATABASE_TYPES"
- redefine_mysql_primary_key "::ActiveRecord::ConnectionAdapters::Mysql2Adapter::NATIVE_DATABASE_TYPES"
+ redefine_mysql_primary_key '::ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::NATIVE_DATABASE_TYPES'
+ redefine_mysql_primary_key '::ActiveRecord::ConnectionAdapters::Mysql2Adapter::NATIVE_DATABASE_TYPES'
end
begin
diff --git a/test/multiverse/suites/active_record/config/database.rb b/test/multiverse/suites/active_record/config/database.rb
index f0d71700a5..57510fe964 100644
--- a/test/multiverse/suites/active_record/config/database.rb
+++ b/test/multiverse/suites/active_record/config/database.rb
@@ -12,9 +12,9 @@
config_dir = File.expand_path(File.dirname(__FILE__))
if defined?(ActiveRecord::VERSION)
- ENV['DATABASE_NAME'] = "multiverse_activerecord_#{ActiveRecord::VERSION::STRING}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr(".", "_")
+ ENV['DATABASE_NAME'] = "multiverse_activerecord_#{ActiveRecord::VERSION::STRING}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr('.', '_')
else
- ENV['DATABASE_NAME'] = "multiverse_activerecord_2_x_#{ENV["MULTIVERSE_ENV"]}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr(".", "_")
+ ENV['DATABASE_NAME'] = "multiverse_activerecord_2_x_#{ENV['MULTIVERSE_ENV']}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr('.', '_')
end
config_raw = File.read(File.join(config_dir, 'database.yml'))
@@ -26,12 +26,12 @@
end
# Rails 2.x didn't keep the Rails out of ActiveRecord much...
-RAILS_ENV = "test"
-RAILS_ROOT = File.join(db_dir, "..")
+RAILS_ENV = 'test'
+RAILS_ROOT = File.join(db_dir, '..')
ActiveRecord::Base.configurations = config_yml
ActiveRecord::Base.establish_connection(:test)
-ActiveRecord::Base.logger = Logger.new(ENV["VERBOSE"] ? STDOUT : StringIO.new)
+ActiveRecord::Base.logger = Logger.new(ENV['VERBOSE'] ? STDOUT : StringIO.new)
begin
load('active_record/railties/databases.rake')
@@ -48,7 +48,7 @@ def self.load_seed
end
end
- DatabaseTasks.env = "test"
+ DatabaseTasks.env = 'test'
DatabaseTasks.db_dir = db_dir
DatabaseTasks.migrations_paths = File.join(db_dir, 'migrate')
DatabaseTasks.database_configuration = config_yml
@@ -63,7 +63,7 @@ def root
end
def env
- ActiveSupport::StringInquirer.new(ENV["RACK_ENV"] || "development")
+ ActiveSupport::StringInquirer.new(ENV['RACK_ENV'] || 'development')
end
def application
@@ -77,7 +77,7 @@ def load_seed
end
end
- Rake::Task.define_task("db:environment")
- Rake::Task["db:load_config"].clear if Rake::Task.task_defined?("db:load_config")
- Rake::Task.define_task("db:rails_env")
+ Rake::Task.define_task('db:environment')
+ Rake::Task['db:load_config'].clear if Rake::Task.task_defined?('db:load_config')
+ Rake::Task.define_task('db:rails_env')
end
diff --git a/test/multiverse/suites/active_record_pg/Rakefile b/test/multiverse/suites/active_record_pg/Rakefile
index a381a6c84a..8ad535f61c 100644
--- a/test/multiverse/suites/active_record_pg/Rakefile
+++ b/test/multiverse/suites/active_record_pg/Rakefile
@@ -4,7 +4,7 @@
require File.expand_path('config/database')
-desc "Setup for ActiveRecord"
+desc 'Setup for ActiveRecord'
task :environment do
if defined?(DatabaseTasks)
ActiveRecord::Base.configurations = DatabaseTasks.database_configuration
diff --git a/test/multiverse/suites/active_record_pg/active_record_test.rb b/test/multiverse/suites/active_record_pg/active_record_test.rb
index 9e17772543..2b64e22ce5 100644
--- a/test/multiverse/suites/active_record_pg/active_record_test.rb
+++ b/test/multiverse/suites/active_record_pg/active_record_test.rb
@@ -158,7 +158,7 @@ def test_metrics_for_find_via_named_scope
def test_metrics_for_exists
in_web_transaction do
- Order.exists?(["name=?", "jeff"])
+ Order.exists?(['name=?', 'jeff'])
end
if active_record_major_version >= 6
@@ -195,7 +195,7 @@ def test_metrics_for_delete_all
def test_metrics_for_relation_delete
in_web_transaction do
- order = Order.create(:name => "lava")
+ order = Order.create(:name => 'lava')
Order.delete(order.id)
end
@@ -204,7 +204,7 @@ def test_metrics_for_relation_delete
def test_metrics_for_delete
in_web_transaction do
- order = Order.create("name" => "burt")
+ order = Order.create('name' => 'burt')
order.delete
end
@@ -217,7 +217,7 @@ def test_metrics_for_delete
def test_metrics_for_touch
in_web_transaction do
- order = Order.create("name" => "wendy")
+ order = Order.create('name' => 'wendy')
order.touch
end
@@ -333,7 +333,7 @@ def test_destroy_via_dependent_destroy
if active_record_version >= Gem::Version.new('4.0.0')
def test_metrics_for_update
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.update(:name => 'walter')
end
@@ -342,7 +342,7 @@ def test_metrics_for_update
def test_metrics_for_update_bang
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.update!(:name => 'walter')
end
@@ -352,7 +352,7 @@ def test_metrics_for_update_bang
def test_metrics_for_update_attribute
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.update_attribute(:name, 'walter')
end
@@ -361,7 +361,7 @@ def test_metrics_for_update_attribute
def test_metrics_for_save
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.name = 'walter'
order.save
end
@@ -371,7 +371,7 @@ def test_metrics_for_save
def test_metrics_for_save_bang
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.name = 'walter'
order.save!
end
@@ -381,18 +381,18 @@ def test_metrics_for_save_bang
def test_nested_metrics_dont_get_model_name
in_web_transaction do
- order = Order.create(:name => "wendy")
+ order = Order.create(:name => 'wendy')
order.name = 'walter'
order.save!
end
- assert_metrics_recorded(["Datastore/operation/Memcached/get"])
+ assert_metrics_recorded(['Datastore/operation/Memcached/get'])
refute_metrics_match(/Memcached.*Order/)
end
def test_metrics_for_destroy
in_web_transaction do
- order = Order.create("name" => "burt")
+ order = Order.create('name' => 'burt')
order.destroy
end
@@ -415,8 +415,8 @@ def test_metrics_for_direct_sql_select
def test_metrics_for_direct_sql_other
in_web_transaction do
conn = Order.connection
- conn.execute("begin")
- conn.execute("commit")
+ conn.execute('begin')
+ conn.execute('commit')
end
assert_generic_rollup_metrics('other')
@@ -426,7 +426,7 @@ def test_metrics_for_direct_sql_show
if supports_show_tables?
in_web_transaction do
conn = Order.connection
- conn.execute("show tables")
+ conn.execute('show tables')
end
assert_generic_rollup_metrics('show')
@@ -437,7 +437,7 @@ def test_still_records_metrics_in_error_cases
# Let's trigger an active record SQL StatementInvalid error
assert_raises ::ActiveRecord::StatementInvalid do
in_web_transaction do
- Order.connection.select_rows("select * from askdjfhkajsdhflkjh")
+ Order.connection.select_rows('select * from askdjfhkajsdhflkjh')
end
end
@@ -464,8 +464,8 @@ def test_only_supportability_metrics_recorded_with_disable_all_tracing
refute last_transaction_trace
assert_metrics_recorded_exclusive([
- "Supportability/API/disable_all_tracing",
- "Supportability/API/drop_buffered_data"
+ 'Supportability/API/disable_all_tracing',
+ 'Supportability/API/drop_buffered_data'
])
end
@@ -569,7 +569,7 @@ def test_cached_calls_are_not_recorded_with_select_all
def test_with_database_metric_name
in_web_transaction do
- Order.create(:name => "eely")
+ Order.create(:name => 'eely')
NewRelic::Agent.with_database_metric_name('Eel', 'squirm') do
Order.connection.select_rows("SELECT id FROM #{Order.table_name}")
end
@@ -626,16 +626,16 @@ def assert_activerecord_metrics(model, operation, stats = {})
assert_metrics_recorded({
"Datastore/statement/#{current_product}/#{model}/#{operation}" => stats,
"Datastore/operation/#{current_product}/#{operation}" => {},
- "Datastore/allWeb" => {},
- "Datastore/all" => {}
+ 'Datastore/allWeb' => {},
+ 'Datastore/all' => {}
})
end
def assert_generic_rollup_metrics(operation)
assert_metrics_recorded([
"Datastore/operation/#{current_product}/#{operation}",
- "Datastore/allWeb",
- "Datastore/all"
+ 'Datastore/allWeb',
+ 'Datastore/all'
])
end
end
diff --git a/test/multiverse/suites/active_record_pg/app/models/models.rb b/test/multiverse/suites/active_record_pg/app/models/models.rb
index 7cb68a0568..8da34c39ec 100644
--- a/test/multiverse/suites/active_record_pg/app/models/models.rb
+++ b/test/multiverse/suites/active_record_pg/app/models/models.rb
@@ -25,7 +25,7 @@ class Order < ActiveRecord::Base
validate :touches_another_datastore
def touches_another_datastore
- NewRelic::Agent::Datastores.wrap("Memcached", "get") do
+ NewRelic::Agent::Datastores.wrap('Memcached', 'get') do
# Fake hitting a cache during validation
end
end
diff --git a/test/multiverse/suites/active_record_pg/ar_method_aliasing.rb b/test/multiverse/suites/active_record_pg/ar_method_aliasing.rb
index 0b229dc15a..03825b084b 100644
--- a/test/multiverse/suites/active_record_pg/ar_method_aliasing.rb
+++ b/test/multiverse/suites/active_record_pg/ar_method_aliasing.rb
@@ -15,7 +15,7 @@ class InstrumentActiveRecordMethods < Minitest::Test
setup_and_teardown_agent
def test_basic_creation
- a_user = User.new(:name => "Bob")
+ a_user = User.new(:name => 'Bob')
assert_predicate a_user, :new_record?
a_user.save!
@@ -25,14 +25,14 @@ def test_basic_creation
end
def test_alias_collection_query_method
- a_user = User.new(:name => "Bob")
+ a_user = User.new(:name => 'Bob')
a_user.save!
a_user = User.first
assert_predicate User, :connected?
- an_alias = Alias.new(:user_id => a_user.id, :aka => "the Blob")
+ an_alias = Alias.new(:user_id => a_user.id, :aka => 'the Blob')
assert_predicate an_alias, :new_record?
an_alias.save!
diff --git a/test/multiverse/suites/active_record_pg/before_suite.rb b/test/multiverse/suites/active_record_pg/before_suite.rb
index f0fc5aa88f..70a2d932ee 100644
--- a/test/multiverse/suites/active_record_pg/before_suite.rb
+++ b/test/multiverse/suites/active_record_pg/before_suite.rb
@@ -4,7 +4,7 @@
def redefine_mysql_primary_key(const_str)
const = Object.const_get(const_str) rescue return
- const[:primary_key] = "int(11) auto_increment PRIMARY KEY"
+ const[:primary_key] = 'int(11) auto_increment PRIMARY KEY'
end
begin
diff --git a/test/multiverse/suites/active_record_pg/config/database.rb b/test/multiverse/suites/active_record_pg/config/database.rb
index f0d71700a5..57510fe964 100644
--- a/test/multiverse/suites/active_record_pg/config/database.rb
+++ b/test/multiverse/suites/active_record_pg/config/database.rb
@@ -12,9 +12,9 @@
config_dir = File.expand_path(File.dirname(__FILE__))
if defined?(ActiveRecord::VERSION)
- ENV['DATABASE_NAME'] = "multiverse_activerecord_#{ActiveRecord::VERSION::STRING}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr(".", "_")
+ ENV['DATABASE_NAME'] = "multiverse_activerecord_#{ActiveRecord::VERSION::STRING}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr('.', '_')
else
- ENV['DATABASE_NAME'] = "multiverse_activerecord_2_x_#{ENV["MULTIVERSE_ENV"]}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr(".", "_")
+ ENV['DATABASE_NAME'] = "multiverse_activerecord_2_x_#{ENV['MULTIVERSE_ENV']}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr('.', '_')
end
config_raw = File.read(File.join(config_dir, 'database.yml'))
@@ -26,12 +26,12 @@
end
# Rails 2.x didn't keep the Rails out of ActiveRecord much...
-RAILS_ENV = "test"
-RAILS_ROOT = File.join(db_dir, "..")
+RAILS_ENV = 'test'
+RAILS_ROOT = File.join(db_dir, '..')
ActiveRecord::Base.configurations = config_yml
ActiveRecord::Base.establish_connection(:test)
-ActiveRecord::Base.logger = Logger.new(ENV["VERBOSE"] ? STDOUT : StringIO.new)
+ActiveRecord::Base.logger = Logger.new(ENV['VERBOSE'] ? STDOUT : StringIO.new)
begin
load('active_record/railties/databases.rake')
@@ -48,7 +48,7 @@ def self.load_seed
end
end
- DatabaseTasks.env = "test"
+ DatabaseTasks.env = 'test'
DatabaseTasks.db_dir = db_dir
DatabaseTasks.migrations_paths = File.join(db_dir, 'migrate')
DatabaseTasks.database_configuration = config_yml
@@ -63,7 +63,7 @@ def root
end
def env
- ActiveSupport::StringInquirer.new(ENV["RACK_ENV"] || "development")
+ ActiveSupport::StringInquirer.new(ENV['RACK_ENV'] || 'development')
end
def application
@@ -77,7 +77,7 @@ def load_seed
end
end
- Rake::Task.define_task("db:environment")
- Rake::Task["db:load_config"].clear if Rake::Task.task_defined?("db:load_config")
- Rake::Task.define_task("db:rails_env")
+ Rake::Task.define_task('db:environment')
+ Rake::Task['db:load_config'].clear if Rake::Task.task_defined?('db:load_config')
+ Rake::Task.define_task('db:rails_env')
end
diff --git a/test/multiverse/suites/activemerchant/activemerchant_test.rb b/test/multiverse/suites/activemerchant/activemerchant_test.rb
index 7c4d6be054..784e059af0 100644
--- a/test/multiverse/suites/activemerchant/activemerchant_test.rb
+++ b/test/multiverse/suites/activemerchant/activemerchant_test.rb
@@ -18,7 +18,7 @@ def update(*_)
class BadGateway < ActiveMerchant::Billing::BogusGateway
def purchase(*args)
super(*args)
- raise StandardError.new("whoops!")
+ raise StandardError.new('whoops!')
end
end
@@ -56,11 +56,11 @@ def test_store
end
def test_unstore
- assert_merchant_transaction(:unstore, "1")
+ assert_merchant_transaction(:unstore, '1')
end
def test_noticed_error_at_segment_and_txn_on_error
- expected_error_class = "StandardError"
+ expected_error_class = 'StandardError'
txn = nil
gateway = BadGateway.new
begin
@@ -77,7 +77,7 @@ def test_noticed_error_at_segment_and_txn_on_error
end
def test_noticed_error_only_at_segment_on_error
- expected_error_class = "StandardError"
+ expected_error_class = 'StandardError'
txn = nil
gateway = BadGateway.new
in_transaction do |local_txn|
@@ -106,8 +106,8 @@ def assert_merchant_transaction(operation, *args)
end
assert_metrics_recorded([
- ["ActiveMerchant/gateway/BogusGateway/#{operation}", "txn"],
- "ActiveMerchant/gateway/BogusGateway",
+ ["ActiveMerchant/gateway/BogusGateway/#{operation}", 'txn'],
+ 'ActiveMerchant/gateway/BogusGateway',
"ActiveMerchant/operation/#{operation}"
])
end
diff --git a/test/multiverse/suites/agent_only/adaptive_sampler_test.rb b/test/multiverse/suites/agent_only/adaptive_sampler_test.rb
index 9752850aa5..ed66dead16 100644
--- a/test/multiverse/suites/agent_only/adaptive_sampler_test.rb
+++ b/test/multiverse/suites/agent_only/adaptive_sampler_test.rb
@@ -31,7 +31,7 @@ def test_adaptive_sampler_valid_stats_and_reset_after_harvest
advance_process_time(60)
- in_transaction("test_txn_20") {}
+ in_transaction('test_txn_20') {}
stats = NewRelic::Agent.instance.adaptive_sampler.stats
diff --git a/test/multiverse/suites/agent_only/agent_attributes_test.rb b/test/multiverse/suites/agent_only/agent_attributes_test.rb
index fc4557498c..01d8837d69 100644
--- a/test/multiverse/suites/agent_only/agent_attributes_test.rb
+++ b/test/multiverse/suites/agent_only/agent_attributes_test.rb
@@ -12,11 +12,11 @@ def test_http_response_code_default_destinations
txn.http_response_code = 418
end
- assert_transaction_trace_has_agent_attribute("http.statusCode", 418)
- assert_event_has_agent_attribute("http.statusCode", 418)
- assert_error_has_agent_attribute("http.statusCode", 418)
+ assert_transaction_trace_has_agent_attribute('http.statusCode', 418)
+ assert_event_has_agent_attribute('http.statusCode', 418)
+ assert_error_has_agent_attribute('http.statusCode', 418)
- refute_browser_monitoring_has_agent_attribute("http.statusCode")
+ refute_browser_monitoring_has_agent_attribute('http.statusCode')
end
def test_response_content_type_default_destinations
@@ -24,11 +24,11 @@ def test_response_content_type_default_destinations
txn.response_content_type = 'application/json'
end
- assert_transaction_trace_has_agent_attribute("response.headers.contentType", "application/json")
- assert_event_has_agent_attribute("response.headers.contentType", "application/json")
- assert_error_has_agent_attribute("response.headers.contentType", "application/json")
+ assert_transaction_trace_has_agent_attribute('response.headers.contentType', 'application/json')
+ assert_event_has_agent_attribute('response.headers.contentType', 'application/json')
+ assert_error_has_agent_attribute('response.headers.contentType', 'application/json')
- refute_browser_monitoring_has_agent_attribute("response.headers.contentType")
+ refute_browser_monitoring_has_agent_attribute('response.headers.contentType')
end
def test_response_content_length_default_destinations
@@ -36,97 +36,97 @@ def test_response_content_length_default_destinations
txn.response_content_length = 100
end
- assert_transaction_trace_has_agent_attribute("response.headers.contentLength", 100)
- assert_event_has_agent_attribute("response.headers.contentLength", 100)
- assert_error_has_agent_attribute("response.headers.contentLength", 100)
+ assert_transaction_trace_has_agent_attribute('response.headers.contentLength', 100)
+ assert_event_has_agent_attribute('response.headers.contentLength', 100)
+ assert_error_has_agent_attribute('response.headers.contentLength', 100)
- refute_browser_monitoring_has_agent_attribute("response.headers.contentLength")
+ refute_browser_monitoring_has_agent_attribute('response.headers.contentLength')
end
def test_request_headers_referer_default_destinations
- txn_options = {:request => stub(:referer => "referrer", :path => "/")}
+ txn_options = {:request => stub(:referer => 'referrer', :path => '/')}
run_transaction({}, txn_options) do |txn|
end
- assert_error_has_agent_attribute("request.headers.referer", "referrer")
+ assert_error_has_agent_attribute('request.headers.referer', 'referrer')
- refute_transaction_trace_has_agent_attribute("request.headers.referer")
- refute_event_has_agent_attribute("request.headers.referer")
- refute_browser_monitoring_has_agent_attribute("request.headers.referer")
+ refute_transaction_trace_has_agent_attribute('request.headers.referer')
+ refute_event_has_agent_attribute('request.headers.referer')
+ refute_browser_monitoring_has_agent_attribute('request.headers.referer')
end
def test_request_parameters_default_destinations_without_capture_params
run_transaction(:capture_params => false) do |txn|
- txn.merge_request_parameters(:duly => "noted")
+ txn.merge_request_parameters(:duly => 'noted')
end
- refute_transaction_trace_has_agent_attribute("request.parameters.duly")
- refute_event_has_agent_attribute("request.parameters.duly")
- refute_error_has_agent_attribute("request.parameters.duly")
- refute_browser_monitoring_has_agent_attribute("request.parameters.duly")
+ refute_transaction_trace_has_agent_attribute('request.parameters.duly')
+ refute_event_has_agent_attribute('request.parameters.duly')
+ refute_error_has_agent_attribute('request.parameters.duly')
+ refute_browser_monitoring_has_agent_attribute('request.parameters.duly')
end
def test_request_parameters_default_destinations_with_capture_params
run_transaction(:capture_params => true) do |txn|
- txn.merge_request_parameters(:duly => "noted")
+ txn.merge_request_parameters(:duly => 'noted')
end
- assert_transaction_trace_has_agent_attribute("request.parameters.duly", "noted")
- assert_error_has_agent_attribute("request.parameters.duly", "noted")
+ assert_transaction_trace_has_agent_attribute('request.parameters.duly', 'noted')
+ assert_error_has_agent_attribute('request.parameters.duly', 'noted')
- refute_event_has_agent_attribute("request.parameters.duly")
- refute_browser_monitoring_has_agent_attribute("request.parameters.duly")
+ refute_event_has_agent_attribute('request.parameters.duly')
+ refute_browser_monitoring_has_agent_attribute('request.parameters.duly')
end
def test_agent_attributes_assigned_from_request
request = stub(
- :path => "/",
- :referer => "http://docs.newrelic.com",
- :env => {"HTTP_ACCEPT" => "application/json"},
+ :path => '/',
+ :referer => 'http://docs.newrelic.com',
+ :env => {'HTTP_ACCEPT' => 'application/json'},
:content_length => 103,
- :content_type => "application/json",
+ :content_type => 'application/json',
:host => 'chippy',
:user_agent => 'Use This!',
- :request_method => "GET"
+ :request_method => 'GET'
)
run_transaction({}, {:request => request}) do |txn|
end
- assert_error_has_agent_attribute "request.headers.referer", "http://docs.newrelic.com"
- refute_transaction_trace_has_agent_attribute "request.headers.referer"
- refute_event_has_agent_attribute "request.headers.referer"
- refute_browser_monitoring_has_agent_attribute "request.headers.referer"
-
- assert_transaction_trace_has_agent_attribute "request.headers.accept", "application/json"
- assert_event_has_agent_attribute "request.headers.accept", "application/json"
- assert_error_has_agent_attribute "request.headers.accept", "application/json"
- refute_browser_monitoring_has_agent_attribute "request.headers.accept"
-
- assert_transaction_trace_has_agent_attribute "request.headers.contentLength", 103
- assert_event_has_agent_attribute "request.headers.contentLength", 103
- assert_error_has_agent_attribute "request.headers.contentLength", 103
- refute_browser_monitoring_has_agent_attribute "request.headers.contentLength"
-
- assert_transaction_trace_has_agent_attribute "request.headers.contentType", "application/json"
- assert_event_has_agent_attribute "request.headers.contentType", "application/json"
- assert_error_has_agent_attribute "request.headers.contentType", "application/json"
- refute_browser_monitoring_has_agent_attribute "request.headers.contentType"
-
- assert_transaction_trace_has_agent_attribute "request.headers.host", "chippy"
- assert_event_has_agent_attribute "request.headers.host", "chippy"
- assert_error_has_agent_attribute "request.headers.host", "chippy"
- refute_browser_monitoring_has_agent_attribute "request.headers.host"
-
- assert_transaction_trace_has_agent_attribute "request.headers.userAgent", "Use This!"
- assert_event_has_agent_attribute "request.headers.userAgent", "Use This!"
- assert_error_has_agent_attribute "request.headers.userAgent", "Use This!"
- refute_browser_monitoring_has_agent_attribute "request.headers.userAgent"
-
- assert_transaction_trace_has_agent_attribute "request.method", "GET"
- assert_event_has_agent_attribute "request.method", "GET"
- assert_error_has_agent_attribute "request.method", "GET"
- refute_browser_monitoring_has_agent_attribute "request.method"
+ assert_error_has_agent_attribute 'request.headers.referer', 'http://docs.newrelic.com'
+ refute_transaction_trace_has_agent_attribute 'request.headers.referer'
+ refute_event_has_agent_attribute 'request.headers.referer'
+ refute_browser_monitoring_has_agent_attribute 'request.headers.referer'
+
+ assert_transaction_trace_has_agent_attribute 'request.headers.accept', 'application/json'
+ assert_event_has_agent_attribute 'request.headers.accept', 'application/json'
+ assert_error_has_agent_attribute 'request.headers.accept', 'application/json'
+ refute_browser_monitoring_has_agent_attribute 'request.headers.accept'
+
+ assert_transaction_trace_has_agent_attribute 'request.headers.contentLength', 103
+ assert_event_has_agent_attribute 'request.headers.contentLength', 103
+ assert_error_has_agent_attribute 'request.headers.contentLength', 103
+ refute_browser_monitoring_has_agent_attribute 'request.headers.contentLength'
+
+ assert_transaction_trace_has_agent_attribute 'request.headers.contentType', 'application/json'
+ assert_event_has_agent_attribute 'request.headers.contentType', 'application/json'
+ assert_error_has_agent_attribute 'request.headers.contentType', 'application/json'
+ refute_browser_monitoring_has_agent_attribute 'request.headers.contentType'
+
+ assert_transaction_trace_has_agent_attribute 'request.headers.host', 'chippy'
+ assert_event_has_agent_attribute 'request.headers.host', 'chippy'
+ assert_error_has_agent_attribute 'request.headers.host', 'chippy'
+ refute_browser_monitoring_has_agent_attribute 'request.headers.host'
+
+ assert_transaction_trace_has_agent_attribute 'request.headers.userAgent', 'Use This!'
+ assert_event_has_agent_attribute 'request.headers.userAgent', 'Use This!'
+ assert_error_has_agent_attribute 'request.headers.userAgent', 'Use This!'
+ refute_browser_monitoring_has_agent_attribute 'request.headers.userAgent'
+
+ assert_transaction_trace_has_agent_attribute 'request.method', 'GET'
+ assert_event_has_agent_attribute 'request.method', 'GET'
+ assert_error_has_agent_attribute 'request.method', 'GET'
+ refute_browser_monitoring_has_agent_attribute 'request.method'
end
def test_custom_attributes_included
@@ -194,46 +194,46 @@ def test_custom_attributes_excluded_with_global_config
def test_request_parameters_captured_on_transaction_events_when_enabled
config = {:'transaction_events.attributes.include' => 'request.parameters.*'}
txn_options = {
- :filtered_params => {:foo => "bar", :bar => "baz"}
+ :filtered_params => {:foo => 'bar', :bar => 'baz'}
}
run_transaction(config, txn_options)
- assert_event_has_agent_attribute("request.parameters.foo", "bar")
- assert_event_has_agent_attribute("request.parameters.bar", "baz")
+ assert_event_has_agent_attribute('request.parameters.foo', 'bar')
+ assert_event_has_agent_attribute('request.parameters.bar', 'baz')
end
def test_request_parameters_captured_in_bam_when_enabled
config = {:'browser_monitoring.attributes.include' => 'request.parameters.*'}
txn_options = {
- :filtered_params => {:foo => "bar", :bar => "baz"}
+ :filtered_params => {:foo => 'bar', :bar => 'baz'}
}
run_transaction(config, txn_options)
- assert_browser_monitoring_has_agent_attribute("request.parameters.foo", "bar")
- assert_browser_monitoring_has_agent_attribute("request.parameters.bar", "baz")
+ assert_browser_monitoring_has_agent_attribute('request.parameters.foo', 'bar')
+ assert_browser_monitoring_has_agent_attribute('request.parameters.bar', 'baz')
end
def test_request_uri_collected_on_default_destinations
config = {}
txn_options = {
- :request => stub(:path => "/foobar")
+ :request => stub(:path => '/foobar')
}
run_transaction(config, txn_options)
last_transaction_trace = single_transaction_trace_posted
- assert_equal "/foobar", last_transaction_trace.uri
- assert_transaction_trace_has_agent_attribute("request.uri", "/foobar")
+ assert_equal '/foobar', last_transaction_trace.uri
+ assert_transaction_trace_has_agent_attribute('request.uri', '/foobar')
- assert_error_has_agent_attribute("request.uri", "/foobar")
- refute_event_has_agent_attribute("request.uri")
- refute_browser_monitoring_has_agent_attribute("request.uri")
+ assert_error_has_agent_attribute('request.uri', '/foobar')
+ refute_event_has_agent_attribute('request.uri')
+ refute_browser_monitoring_has_agent_attribute('request.uri')
end
def test_request_uri_can_be_disabled_on_tts
config = {:'transaction_tracer.attributes.exclude' => 'request.uri'}
txn_options = {
- :request => stub(:path => "/foobar")
+ :request => stub(:path => '/foobar')
}
run_transaction(config, txn_options)
@@ -241,40 +241,40 @@ def test_request_uri_can_be_disabled_on_tts
refute last_transaction_trace.uri
- assert_error_has_agent_attribute("request.uri", "/foobar")
- refute_transaction_trace_has_agent_attribute("request.uri")
- refute_event_has_agent_attribute("request.uri")
- refute_browser_monitoring_has_agent_attribute("request.uri")
+ assert_error_has_agent_attribute('request.uri', '/foobar')
+ refute_transaction_trace_has_agent_attribute('request.uri')
+ refute_event_has_agent_attribute('request.uri')
+ refute_browser_monitoring_has_agent_attribute('request.uri')
end
def test_request_uri_can_be_disabled_on_error_traces
config = {:'error_collector.attributes.exclude' => 'request.uri'}
txn_options = {
- :request => stub(:path => "/foobar")
+ :request => stub(:path => '/foobar')
}
run_transaction(config, txn_options)
last_error_trace = single_error_posted
- refute last_error_trace.params["agentAttributes"]["request.uri"]
+ refute last_error_trace.params['agentAttributes']['request.uri']
- assert_transaction_trace_has_agent_attribute("request.uri", "/foobar")
- refute_error_has_agent_attribute("request.uri")
- refute_event_has_agent_attribute("request.uri")
- refute_browser_monitoring_has_agent_attribute("request.uri")
+ assert_transaction_trace_has_agent_attribute('request.uri', '/foobar')
+ refute_error_has_agent_attribute('request.uri')
+ refute_event_has_agent_attribute('request.uri')
+ refute_browser_monitoring_has_agent_attribute('request.uri')
end
def test_request_uri_can_be_disabled_by_global_attributes_config
config = {:'attributes.exclude' => 'request.uri'}
txn_options = {
- :request => stub(:path => "/foobar")
+ :request => stub(:path => '/foobar')
}
run_transaction(config, txn_options)
- refute_transaction_trace_has_agent_attribute("request.uri")
- refute_error_has_agent_attribute("request.uri")
- refute_event_has_agent_attribute("request.uri")
- refute_browser_monitoring_has_agent_attribute("request.uri")
+ refute_transaction_trace_has_agent_attribute('request.uri')
+ refute_error_has_agent_attribute('request.uri')
+ refute_event_has_agent_attribute('request.uri')
+ refute_browser_monitoring_has_agent_attribute('request.uri')
end
def test_http_response_code_excluded_in_txn_events_when_disabled
@@ -322,7 +322,7 @@ def run_transaction(config = {}, txn_options = {})
capture_js_data
# Have to raise an error to exercise attribute capture there
- raise "O_o"
+ raise 'O_o'
end
end
end
diff --git a/test/multiverse/suites/agent_only/agent_run_id_handling_test.rb b/test/multiverse/suites/agent_only/agent_run_id_handling_test.rb
index b877271ddd..dc5a804966 100644
--- a/test/multiverse/suites/agent_only/agent_run_id_handling_test.rb
+++ b/test/multiverse/suites/agent_only/agent_run_id_handling_test.rb
@@ -10,7 +10,7 @@ class AgentRunIdHandlingTest < Minitest::Test
NON_NUMERIC_RUN_ID = 'some-crazy-non-integer-thing'
setup_and_teardown_agent do
- $collector.stub('connect', {"agent_run_id" => NON_NUMERIC_RUN_ID})
+ $collector.stub('connect', {'agent_run_id' => NON_NUMERIC_RUN_ID})
end
# This test verifies that the Ruby agent is able to accept non-numeric values
@@ -34,7 +34,7 @@ def test_handles_non_numeric_agent_run_id_on_slow_sql_traces
def simulate_slow_sql_trace
in_transaction do
- agent.sql_sampler.notice_sql("select * from test", "Database/test/select", nil, 1.5)
+ agent.sql_sampler.notice_sql('select * from test', 'Database/test/select', nil, 1.5)
end
NewRelic::Agent.agent.send(:harvest_and_send_slowest_sql)
end
diff --git a/test/multiverse/suites/agent_only/audit_log_test.rb b/test/multiverse/suites/agent_only/audit_log_test.rb
index ddcd1b218d..0ec7a3d4d7 100644
--- a/test/multiverse/suites/agent_only/audit_log_test.rb
+++ b/test/multiverse/suites/agent_only/audit_log_test.rb
@@ -55,8 +55,8 @@ def test_logs_request_bodies_human_readably_ish
def perform_actions
state = NewRelic::Agent::Tracer.state
NewRelic::Agent.instance.sql_sampler.on_start_transaction(state)
- NewRelic::Agent.instance.sql_sampler.notice_sql("select * from test",
- "Database/test/select",
+ NewRelic::Agent.instance.sql_sampler.notice_sql('select * from test',
+ 'Database/test/select',
nil, 1.5, state)
NewRelic::Agent.instance.sql_sampler.on_finishing_transaction(state, 'txn')
NewRelic::Agent.instance.send(:harvest_and_send_slowest_sql)
diff --git a/test/multiverse/suites/agent_only/cross_application_tracing_test.rb b/test/multiverse/suites/agent_only/cross_application_tracing_test.rb
index a294d599c8..7ac4a14064 100644
--- a/test/multiverse/suites/agent_only/cross_application_tracing_test.rb
+++ b/test/multiverse/suites/agent_only/cross_application_tracing_test.rb
@@ -11,14 +11,14 @@ class CrossApplicationTracingTest < Minitest::Test
include MultiverseHelpers
setup_and_teardown_agent(:'cross_application_tracer.enabled' => true,
:'distributed_tracing.enabled' => false,
- :cross_process_id => "boo",
+ :cross_process_id => 'boo',
:encoding_key => "\0",
:trusted_account_ids => [1]) \
do |collector|
collector.stub('connect', {
'agent_run_id' => 666,
- 'transaction_name_rules' => [{"match_expression" => "ignored_transaction",
- "ignore" => true}]
+ 'transaction_name_rules' => [{'match_expression' => 'ignored_transaction',
+ 'ignore' => true}]
})
end
@@ -31,26 +31,26 @@ def app
def test_cross_app_doesnt_modify_without_header
get('/')
- refute last_response.headers["X-NewRelic-App-Data"]
+ refute last_response.headers['X-NewRelic-App-Data']
end
def test_cross_app_doesnt_modify_with_invalid_header
get('/', nil, {'HTTP_X_NEWRELIC_ID' => Base64.encode64('otherjunk')})
- refute last_response.headers["X-NewRelic-App-Data"]
+ refute last_response.headers['X-NewRelic-App-Data']
end
def test_cross_app_writes_out_information
get('/', nil, {'HTTP_X_NEWRELIC_ID' => Base64.encode64('1#234')})
- refute_nil last_response.headers["X-NewRelic-App-Data"]
+ refute_nil last_response.headers['X-NewRelic-App-Data']
assert_metrics_recorded(['ClientApplication/1#234/all'])
end
def test_cross_app_doesnt_modify_if_txn_is_ignored
get('/', {'transaction_name' => 'ignored_transaction'}, {'HTTP_X_NEWRELIC_ID' => Base64.encode64('1#234')})
- refute last_response.headers["X-NewRelic-App-Data"]
+ refute last_response.headers['X-NewRelic-App-Data']
end
def test_cross_app_error_attaches_process_id_to_intrinsics
@@ -61,9 +61,9 @@ def test_cross_app_error_attaches_process_id_to_intrinsics
assert_includes attributes_for(last_traced_error, :intrinsic), :client_cross_process_id
end
- load_cross_agent_test("cat_map").each do |test_case|
+ load_cross_agent_test('cat_map').each do |test_case|
# We only can do test cases here that don't involve outgoing calls
- if !test_case["outboundRequests"]
+ if !test_case['outboundRequests']
if test_case['inboundPayload']
request_headers = {
'HTTP_X_NEWRELIC_ID' => Base64.encode64('1#234'),
diff --git a/test/multiverse/suites/agent_only/custom_analytics_events_test.rb b/test/multiverse/suites/agent_only/custom_analytics_events_test.rb
index 1cc7050196..8898a9c029 100644
--- a/test/multiverse/suites/agent_only/custom_analytics_events_test.rb
+++ b/test/multiverse/suites/agent_only/custom_analytics_events_test.rb
@@ -75,7 +75,7 @@ def test_post_includes_metadata
NewRelic::Agent.agent.send(:harvest_and_send_custom_event_data)
post = last_custom_event_post
- assert_equal({"reservoir_size" => 3000, "events_seen" => 10}, post.reservoir_metadata)
+ assert_equal({'reservoir_size' => 3000, 'events_seen' => 10}, post.reservoir_metadata)
end
def last_custom_event_post
diff --git a/test/multiverse/suites/agent_only/custom_queue_time_test.rb b/test/multiverse/suites/agent_only/custom_queue_time_test.rb
index fd045d99f8..6c10401289 100644
--- a/test/multiverse/suites/agent_only/custom_queue_time_test.rb
+++ b/test/multiverse/suites/agent_only/custom_queue_time_test.rb
@@ -11,7 +11,7 @@ class CustomQueueTimeTest < Minitest::Test
DummyRequest = Struct.new(:headers, :cookies) do
def path
- "/"
+ '/'
end
end
diff --git a/test/multiverse/suites/agent_only/encoding_handling_test.rb b/test/multiverse/suites/agent_only/encoding_handling_test.rb
index 49a12b2d96..efb4add481 100644
--- a/test/multiverse/suites/agent_only/encoding_handling_test.rb
+++ b/test/multiverse/suites/agent_only/encoding_handling_test.rb
@@ -130,7 +130,7 @@ def object_graph_contains_string?(object_graph, string)
end
def bad_string
- [128].to_a.pack("C*").force_encoding('UTF-8')
+ [128].to_a.pack('C*').force_encoding('UTF-8')
end
def normalized_bad_string
diff --git a/test/multiverse/suites/agent_only/error_events_test.rb b/test/multiverse/suites/agent_only/error_events_test.rb
index 4c5124ba06..0309cbfd88 100644
--- a/test/multiverse/suites/agent_only/error_events_test.rb
+++ b/test/multiverse/suites/agent_only/error_events_test.rb
@@ -16,12 +16,12 @@ def test_error_events_are_submitted
intrinsics, _, _ = last_error_event
- assert_equal txn.best_name, intrinsics["transactionName"]
- assert_equal "RuntimeError", intrinsics["error.class"]
- assert_equal "Big Controller", intrinsics["error.message"]
- refute intrinsics["error.expected"]
- assert_equal "TransactionError", intrinsics["type"]
- assert_equal txn.payload[:duration], intrinsics["duration"]
+ assert_equal txn.best_name, intrinsics['transactionName']
+ assert_equal 'RuntimeError', intrinsics['error.class']
+ assert_equal 'Big Controller', intrinsics['error.message']
+ refute intrinsics['error.expected']
+ assert_equal 'TransactionError', intrinsics['type']
+ assert_equal txn.payload[:duration], intrinsics['duration']
end
def test_error_events_honor_expected_option
@@ -31,7 +31,7 @@ def test_error_events_honor_expected_option
intrinsics, _, _ = last_error_event
- assert intrinsics["error.expected"]
+ assert intrinsics['error.expected']
end
def test_records_supportability_metrics
@@ -41,8 +41,8 @@ def test_records_supportability_metrics
NewRelic::Agent.agent.send(:harvest_and_send_error_event_data)
assert_metrics_recorded({
- "Supportability/Events/TransactionError/Sent" => {:call_count => 10},
- "Supportability/Events/TransactionError/Seen" => {:call_count => 15}
+ 'Supportability/Events/TransactionError/Sent' => {:call_count => 10},
+ 'Supportability/Events/TransactionError/Seen' => {:call_count => 15}
})
end
end
@@ -94,21 +94,21 @@ def test_does_not_record_error_events_when_disabled_by_feature_gate
end
def test_error_events_created_outside_of_transaction
- NewRelic::Agent.notice_error(RuntimeError.new("No Txn"))
+ NewRelic::Agent.notice_error(RuntimeError.new('No Txn'))
NewRelic::Agent.agent.send(:harvest_and_send_error_event_data)
intrinsics, _, _ = last_error_event
- assert_equal "TransactionError", intrinsics["type"]
- assert_in_delta Process.clock_gettime(Process::CLOCK_REALTIME), intrinsics["timestamp"], 0.001
- assert_equal "RuntimeError", intrinsics["error.class"]
- assert_equal "No Txn", intrinsics["error.message"]
- assert intrinsics["priority"], "Priority is nil"
+ assert_equal 'TransactionError', intrinsics['type']
+ assert_in_delta Process.clock_gettime(Process::CLOCK_REALTIME), intrinsics['timestamp'], 0.001
+ assert_equal 'RuntimeError', intrinsics['error.class']
+ assert_equal 'No Txn', intrinsics['error.message']
+ assert intrinsics['priority'], 'Priority is nil'
end
def test_error_events_during_txn_abide_by_custom_attributes_config
with_config(:'custom_attributes.enabled' => false) do
- generate_errors(1, {:foo => "bar"})
+ generate_errors(1, {:foo => 'bar'})
end
NewRelic::Agent.agent.send(:harvest_and_send_error_event_data)
@@ -120,7 +120,7 @@ def test_error_events_during_txn_abide_by_custom_attributes_config
def test_error_events_outside_txn_abide_by_custom_attributes_config
with_config(:'custom_attributes.enabled' => false) do
- NewRelic::Agent.notice_error(RuntimeError.new("Big Controller"), {:foo => "bar"})
+ NewRelic::Agent.notice_error(RuntimeError.new('Big Controller'), {:foo => 'bar'})
end
NewRelic::Agent.agent.send(:harvest_and_send_error_event_data)
@@ -131,8 +131,8 @@ def test_error_events_outside_txn_abide_by_custom_attributes_config
end
def generate_errors(num_errors = 1, options = {})
- in_transaction(:transaction_name => "Controller/blogs/index") do |t|
- num_errors.times { t.notice_error(RuntimeError.new("Big Controller"), options) }
+ in_transaction(:transaction_name => 'Controller/blogs/index') do |t|
+ num_errors.times { t.notice_error(RuntimeError.new('Big Controller'), options) }
end
end
diff --git a/test/multiverse/suites/agent_only/event_data_collection_test.rb b/test/multiverse/suites/agent_only/event_data_collection_test.rb
index cf0c1f1430..73f2080f12 100644
--- a/test/multiverse/suites/agent_only/event_data_collection_test.rb
+++ b/test/multiverse/suites/agent_only/event_data_collection_test.rb
@@ -10,11 +10,11 @@ class EventDataCollectionTest < Minitest::Test
def test_sends_all_event_capacities_on_connect
expected = {
'harvest_limits' => {
- "analytic_event_data" => 1200,
- "custom_event_data" => 3000,
- "error_event_data" => 100,
- "span_event_data" => 2000,
- "log_event_data" => 10000
+ 'analytic_event_data' => 1200,
+ 'custom_event_data' => 3000,
+ 'error_event_data' => 100,
+ 'span_event_data' => 2000,
+ 'log_event_data' => 10000
}
}
@@ -25,14 +25,14 @@ def test_sends_all_event_capacities_on_connect
def test_sets_event_report_period_on_connect_response
connect_response = {
- "agent_run_id" => 1,
- "event_harvest_config" => {
- "report_period_ms" => 5000,
- "harvest_limits" => {
- "analytic_event_data" => 1200,
- "custom_event_data" => 3000,
- "error_event_data" => 100,
- "log_event_data" => 10000
+ 'agent_run_id' => 1,
+ 'event_harvest_config' => {
+ 'report_period_ms' => 5000,
+ 'harvest_limits' => {
+ 'analytic_event_data' => 1200,
+ 'custom_event_data' => 3000,
+ 'error_event_data' => 100,
+ 'log_event_data' => 10000
}
}
}
@@ -46,14 +46,14 @@ def test_sets_event_report_period_on_connect_response
def test_resets_event_report_period_on_reconnect
connect_response = {
- "agent_run_id" => 1,
- "event_harvest_config" => {
- "report_period_ms" => 5000,
- "harvest_limits" => {
- "analytic_event_data" => 1200,
- "custom_event_data" => 3000,
- "error_event_data" => 100,
- "log_event_data" => 10000
+ 'agent_run_id' => 1,
+ 'event_harvest_config' => {
+ 'report_period_ms' => 5000,
+ 'harvest_limits' => {
+ 'analytic_event_data' => 1200,
+ 'custom_event_data' => 3000,
+ 'error_event_data' => 100,
+ 'log_event_data' => 10000
}
}
}
diff --git a/test/multiverse/suites/agent_only/harvest_timestamps_test.rb b/test/multiverse/suites/agent_only/harvest_timestamps_test.rb
index 378ac27228..a46528954e 100644
--- a/test/multiverse/suites/agent_only/harvest_timestamps_test.rb
+++ b/test/multiverse/suites/agent_only/harvest_timestamps_test.rb
@@ -56,6 +56,6 @@ def last_metric_data_post
end
def simulate_fork
- NewRelic::Agent.instance.harvester.instance_variable_set(:@starting_pid, nil)
+ NewRelic::Agent.instance.instance_variable_get(:@harvester).instance_variable_set(:@starting_pid, nil)
end
end
diff --git a/test/multiverse/suites/agent_only/labels_test.rb b/test/multiverse/suites/agent_only/labels_test.rb
index f3e5282c77..09900d744d 100644
--- a/test/multiverse/suites/agent_only/labels_test.rb
+++ b/test/multiverse/suites/agent_only/labels_test.rb
@@ -20,7 +20,7 @@ def test_yaml_makes_it_to_the_collector
end
def test_labels_from_config_hash_make_it_to_the_collector
- with_config("labels" => {"Server" => "East"}) do
+ with_config('labels' => {'Server' => 'East'}) do
trigger_agent_reconnect
assert_connect_had_labels(EXPECTED)
@@ -28,13 +28,13 @@ def test_labels_from_config_hash_make_it_to_the_collector
end
def test_labels_from_manual_start_hash_make_it_to_the_collector
- trigger_agent_reconnect(:labels => {"Server" => "East"})
+ trigger_agent_reconnect(:labels => {'Server' => 'East'})
assert_connect_had_labels(EXPECTED)
end
def test_numeric_values_for_labels
- trigger_agent_reconnect(:labels => {"Server" => 42})
+ trigger_agent_reconnect(:labels => {'Server' => 42})
expected = [
{'label_type' => 'Server', 'label_value' => '42'}
]
@@ -43,7 +43,7 @@ def test_numeric_values_for_labels
end
def test_boolean_values_for_labels
- trigger_agent_reconnect(:labels => {"Server" => true})
+ trigger_agent_reconnect(:labels => {'Server' => true})
expected = [
{'label_type' => 'Server', 'label_value' => 'true'}
]
@@ -53,30 +53,30 @@ def test_boolean_values_for_labels
# All testing of string parsed label pairs should go through the cross agent
# test file for labels. Our dictionary passing is custom to Ruby, though.
- load_cross_agent_test("labels").each do |testcase|
+ load_cross_agent_test('labels').each do |testcase|
define_method("test_#{testcase['name']}_from_config_string") do
- with_config("labels" => testcase["labelString"]) do
+ with_config('labels' => testcase['labelString']) do
trigger_agent_reconnect
- assert_connect_had_labels(testcase["expected"])
+ assert_connect_had_labels(testcase['expected'])
end
end
define_method("test_#{testcase['name']}_from_manual_start") do
- trigger_agent_reconnect(:labels => testcase["labelString"])
+ trigger_agent_reconnect(:labels => testcase['labelString'])
- assert_connect_had_labels(testcase["expected"])
+ assert_connect_had_labels(testcase['expected'])
end
define_method("test_#{testcase['name']}_from_env") do
begin
# Value must be here before reset for EnvironmentSource to see it
- ENV['NEW_RELIC_LABELS'] = testcase["labelString"]
+ ENV['NEW_RELIC_LABELS'] = testcase['labelString']
NewRelic::Agent.config.reset_to_defaults
trigger_agent_reconnect
- assert_connect_had_labels(testcase["expected"])
+ assert_connect_had_labels(testcase['expected'])
ensure
ENV['NEW_RELIC_LABELS'] = nil
end
diff --git a/test/multiverse/suites/agent_only/log_events_test.rb b/test/multiverse/suites/agent_only/log_events_test.rb
index 24b4c20dbf..6abd994384 100644
--- a/test/multiverse/suites/agent_only/log_events_test.rb
+++ b/test/multiverse/suites/agent_only/log_events_test.rb
@@ -13,7 +13,7 @@ def test_log_event_data_sent_in_transaction
with_config(:'application_logging.forwarding.enabled' => true) do
in_transaction do |txn|
NewRelic::Agent.agent.log_event_aggregator.reset!
- NewRelic::Agent.agent.log_event_aggregator.record("Deadly", "FATAL")
+ NewRelic::Agent.agent.log_event_aggregator.record('Deadly', 'FATAL')
trace_id = NewRelic::Agent::Tracer.current_trace_id
span_id = NewRelic::Agent::Tracer.current_span_id
end
@@ -23,35 +23,35 @@ def test_log_event_data_sent_in_transaction
last_log = last_log_event
- assert_equal "Deadly", last_log["message"]
- assert_equal "FATAL", last_log["level"]
- assert_equal trace_id, last_log["trace.id"]
- assert_equal span_id, last_log["span.id"]
+ assert_equal 'Deadly', last_log['message']
+ assert_equal 'FATAL', last_log['level']
+ assert_equal trace_id, last_log['trace.id']
+ assert_equal span_id, last_log['span.id']
common = last_logs_common
- assert_nil common["attributes"]["entity.type"]
- assert_equal NewRelic::Agent::Hostname.get, common["attributes"]["hostname"]
+ assert_nil common['attributes']['entity.type']
+ assert_equal NewRelic::Agent::Hostname.get, common['attributes']['hostname']
end
def test_log_event_data_sent_no_transaction
NewRelic::Agent.agent.log_event_aggregator.reset!
with_config(:'application_logging.forwarding.enabled' => true) do
- NewRelic::Agent.agent.log_event_aggregator.record("Deadly", "FATAL")
+ NewRelic::Agent.agent.log_event_aggregator.record('Deadly', 'FATAL')
NewRelic::Agent.agent.send(:harvest_and_send_log_event_data)
end
last_log = last_log_event
- assert_equal "Deadly", last_log["message"]
- assert_equal "FATAL", last_log["level"]
- assert_nil last_log["trace.id"]
- assert_nil last_log["span.id"]
+ assert_equal 'Deadly', last_log['message']
+ assert_equal 'FATAL', last_log['level']
+ assert_nil last_log['trace.id']
+ assert_nil last_log['span.id']
common = last_logs_common
- assert_nil common["attributes"]["entity.type"]
- assert_equal NewRelic::Agent::Hostname.get, common["attributes"]["hostname"]
+ assert_nil common['attributes']['entity.type']
+ assert_equal NewRelic::Agent::Hostname.get, common['attributes']['hostname']
end
def last_log_event
diff --git a/test/multiverse/suites/agent_only/logging_test.rb b/test/multiverse/suites/agent_only/logging_test.rb
index 2346a99e5b..4e057d83f3 100644
--- a/test/multiverse/suites/agent_only/logging_test.rb
+++ b/test/multiverse/suites/agent_only/logging_test.rb
@@ -23,20 +23,20 @@ def teardown
def test_logs_app_name
running_agent_writes_to_log(
- {:app_name => "My App"},
- "Application: My App"
+ {:app_name => 'My App'},
+ 'Application: My App'
)
end
def test_logs_error_with_bad_app_name
running_agent_writes_to_log(
{:app_name => false},
- "No application name configured."
+ 'No application name configured.'
)
end
def test_logs_dispatcher
- dispatcher = "Y U NO SERVER WEBPAGE"
+ dispatcher = 'Y U NO SERVER WEBPAGE'
running_agent_writes_to_log(
{:dispatcher => dispatcher},
@@ -47,14 +47,14 @@ def test_logs_dispatcher
def test_logs_missing_dispatcher
running_agent_writes_to_log(
{:dispatcher => ''},
- "No known dispatcher detected"
+ 'No known dispatcher detected'
)
end
def test_logs_raw_sql_warning
running_agent_writes_to_log(
{:'transaction_tracer.record_sql' => 'obfuscated'},
- "Agent is configured to send raw SQL to the service"
+ 'Agent is configured to send raw SQL to the service'
) do
NewRelic::Agent.config.add_config_for_testing(:'transaction_tracer.record_sql' => 'raw')
end
@@ -63,7 +63,7 @@ def test_logs_raw_sql_warning
def test_logs_if_sending_errors_on_change
running_agent_writes_to_log(
{:'error_collector.enabled' => false},
- "Error traces will be sent"
+ 'Error traces will be sent'
) do
NewRelic::Agent.config.add_config_for_testing(:'error_collector.enabled' => true)
end
@@ -72,7 +72,7 @@ def test_logs_if_sending_errors_on_change
def test_logs_if_not_sending_errors_on_change
running_agent_writes_to_log(
{:'error_collector.enabled' => true},
- "Error traces will not be sent"
+ 'Error traces will not be sent'
) do
NewRelic::Agent.config.add_config_for_testing(:'error_collector.enabled' => false)
end
@@ -81,7 +81,7 @@ def test_logs_if_not_sending_errors_on_change
def test_logs_transaction_tracing_disabled
running_agent_writes_to_log(
{:'transaction_tracer.enabled' => false},
- "Transaction traces will not be sent"
+ 'Transaction traces will not be sent'
)
end
@@ -90,7 +90,7 @@ def test_invalid_license_key
collector.stub('connect', {}, 410)
end
- saw?("Agent received a ForceDisconnectException from the server")
+ saw?('Agent received a ForceDisconnectException from the server')
teardown_agent
end
@@ -98,28 +98,28 @@ def test_invalid_license_key
def test_logs_monitor_mode_disabled
running_agent_writes_to_log(
{:monitor_mode => false},
- "Agent configured not to send data in this environment."
+ 'Agent configured not to send data in this environment.'
)
end
def test_logs_missing_license_key
running_agent_writes_to_log(
{:license_key => false},
- "No license key found."
+ 'No license key found.'
)
end
def test_logs_blank_license_key
running_agent_writes_to_log(
{:license_key => ''},
- "No license key found."
+ 'No license key found.'
)
end
def test_logs_invalid_license_key
running_agent_writes_to_log(
{:license_key => 'a' * 30},
- "Invalid license key: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ 'Invalid license key: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
)
end
@@ -137,7 +137,7 @@ def test_logs_unknown_config_setting_from_environment
def test_logs_forking_workers
running_agent_writes_to_log(
{:dispatcher => :passenger},
- "Deferring startup of agent reporting thread"
+ 'Deferring startup of agent reporting thread'
)
end
diff --git a/test/multiverse/suites/agent_only/marshaling_test.rb b/test/multiverse/suites/agent_only/marshaling_test.rb
index b0fb5c6c73..58de946446 100644
--- a/test/multiverse/suites/agent_only/marshaling_test.rb
+++ b/test/multiverse/suites/agent_only/marshaling_test.rb
@@ -70,7 +70,7 @@ def test_error_data_marshalling
def test_sql_trace_data_marshalling
in_transaction do
- agent.sql_sampler.notice_sql("select * from test", "Database/test/select",
+ agent.sql_sampler.notice_sql('select * from test', 'Database/test/select',
nil, 1.5)
end
diff --git a/test/multiverse/suites/agent_only/rename_rule_test.rb b/test/multiverse/suites/agent_only/rename_rule_test.rb
index 0f3d4275da..519c05bab3 100644
--- a/test/multiverse/suites/agent_only/rename_rule_test.rb
+++ b/test/multiverse/suites/agent_only/rename_rule_test.rb
@@ -59,7 +59,7 @@ def test_metric_name_rules
def test_transaction_segment_terms_do_not_apply_to_metrics
in_transaction do
- NewRelic::Agent.record_metric("other/qux/foo/bar", 42)
+ NewRelic::Agent.record_metric('other/qux/foo/bar', 42)
end
assert_metrics_recorded(['other/qux/foo/bar'])
diff --git a/test/multiverse/suites/agent_only/rum_instrumentation_test.rb b/test/multiverse/suites/agent_only/rum_instrumentation_test.rb
index ea2f32ac03..a84497b165 100644
--- a/test/multiverse/suites/agent_only/rum_instrumentation_test.rb
+++ b/test/multiverse/suites/agent_only/rum_instrumentation_test.rb
@@ -12,7 +12,7 @@ class RumAutoTest < Minitest::Test
include Rack::Test::Methods
include MultiverseHelpers
- JS_AGENT_LOADER = "JS_AGENT_LOADER"
+ JS_AGENT_LOADER = 'JS_AGENT_LOADER'
LOADER_REGEX = "\nJS_AGENT_LOADER"
CONFIG_REGEX = "\n.*NREUM.info=.*"
@@ -22,8 +22,8 @@ class RumAutoTest < Minitest::Test
:browser_key => 'browserKey',
:js_agent_loader => JS_AGENT_LOADER) do |collector|
collector.stub('connect', {
- 'transaction_name_rules' => [{"match_expression" => "ignored_transaction",
- "ignore" => true}],
+ 'transaction_name_rules' => [{'match_expression' => 'ignored_transaction',
+ 'ignore' => true}],
'agent_run_id' => 1
})
end
@@ -34,21 +34,21 @@ def after_setup
end
def test_autoinstrumentation_is_active
- @inner_app.response = "W00t!Hello World
"
+ @inner_app.response = 'W00t!Hello World
'
get('/')
- assert_response_includes("