diff --git a/lib/mongo/server/app_metadata/environment.rb b/lib/mongo/server/app_metadata/environment.rb index a5c0be4a79..79bc9667d9 100644 --- a/lib/mongo/server/app_metadata/environment.rb +++ b/lib/mongo/server/app_metadata/environment.rb @@ -42,6 +42,10 @@ class TypeMismatch < Mongo::Error; end # Error class for reporting that the value for a field is too long. class ValueTooLong < Mongo::Error; end + # The name and location of the .dockerenv file that will signal the + # presence of Docker. + DOCKERENV_PATH = '/.dockerenv'.freeze + # This value is not explicitly specified in the spec, only implied to be # less than 512. MAXIMUM_VALUE_LENGTH = 500 @@ -212,7 +216,7 @@ def detect_environment end # Looks for the presence of a container. Currently can detect - # Docker (by the existence of a Dockerfile in the working + # Docker (by the existence of a .dockerenv file in the root # directory) and Kubernetes (by the existence of the KUBERNETES_SERVICE_HOST # environment variable). def detect_container @@ -228,7 +232,13 @@ def detect_container # Checks for the existence of a Dockerfile in the working directory. def docker_present? - File.exist?('Dockerfile') + File.exist?(dockerenv_path) + end + + # Implementing this as a method so that it can be mocked in tests, to + # test the presence or absence of Docker. + def dockerenv_path + DOCKERENV_PATH end # Checks for the presence of a non-empty KUBERNETES_SERVICE_HOST diff --git a/spec/mongo/server/app_metadata/environment_spec.rb b/spec/mongo/server/app_metadata/environment_spec.rb index 4378b3b320..bdf0194d98 100644 --- a/spec/mongo/server/app_metadata/environment_spec.rb +++ b/spec/mongo/server/app_metadata/environment_spec.rb @@ -3,24 +3,34 @@ require 'spec_helper' require 'fileutils' +MOCKED_DOCKERENV_PATH = File.expand_path(File.join(Dir.pwd, '.dockerenv-mocked')) + module ContainerChecking + def mock_dockerenv_path + before do + allow_any_instance_of(Mongo::Server::AppMetadata::Environment) + .to receive(:dockerenv_path) + .and_return(MOCKED_DOCKERENV_PATH) + end + end + def with_docker + mock_dockerenv_path + around do |example| - keep = File.exist?('Dockerfile') - File.write('Dockerfile', 'placeholder') unless keep + File.write(MOCKED_DOCKERENV_PATH, 'placeholder') example.run ensure - File.delete('Dockerfile') unless keep + File.delete(MOCKED_DOCKERENV_PATH) end end def without_docker + mock_dockerenv_path + around do |example| - save = 'Dockerfile' if File.exist?('Dockerfile') - FileUtils.mv('Dockerfile', '_Dockerfile') if save + FileUtils.rm_f(MOCKED_DOCKERENV_PATH) example.run - ensure - FileUtils.mv('_Dockerfile', 'Dockerfile') if save end end