Created
September 24, 2020 20:45
-
-
Save paulmakepeace/7f7c9f1710c34e1c3d909f567fc1bbc1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# DockerHelper provides methods to work with Docker containers. | |
module DockerHelper | |
extend self | |
def running_in_docker? | |
!!(File.read("/proc/1/cgroup") =~ %r[^\d+:\w+:/docker/]) # !! => true/false | |
rescue Errno::ENOENT | |
false | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require "spec_helper" | |
RSpec.describe DockerHelper do | |
let(:cgroup_docker) do | |
<<~CGROUP | |
3:cpuacct:/docker/deadbeef | |
2:cpu:/docker/acecafe8 | |
1:cpuset:/docker/104decaf | |
CGROUP | |
end | |
let(:cgroup_linux) do | |
<<~CGROUP | |
3:cpu,cpuacct:/init.scope | |
2:devices:/init.scope | |
1:name=systemd:/init.scope | |
CGROUP | |
end | |
it "detects running on Docker" do | |
# /proc/1/cgroup contains Docker strings | |
allow(File).to receive(:read).and_return(cgroup_docker) | |
expect(DockerHelper.running_in_docker?).to eq(true) | |
end | |
it "detects not running on Docker (Linux)" do | |
# /proc/1/cgroup contains non-Docker strings | |
allow(File).to receive(:read).and_return(cgroup_linux) | |
expect(DockerHelper.running_in_docker?).to eq(false) | |
end | |
it "detects not running on Docker (macOS)" do | |
# /proc/1/cgroup doesn't exist | |
allow(File).to receive(:read).and_raise(Errno::ENOENT) | |
expect(DockerHelper.running_in_docker?).to eq(false) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment