Skip to content

Commit

Permalink
look for .dockerenv, not Dockerfile
Browse files Browse the repository at this point in the history
  • Loading branch information
jamis committed Jan 11, 2024
1 parent 9b42ffa commit 75a7baf
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
14 changes: 12 additions & 2 deletions lib/mongo/server/app_metadata/environment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
24 changes: 17 additions & 7 deletions spec/mongo/server/app_metadata/environment_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 75a7baf

Please sign in to comment.