Skip to content

Commit

Permalink
fix(Containers resolver): properly detect Docker runtime in containers (
Browse files Browse the repository at this point in the history
#2781)

Previously, the `Containers` resolver would always return a value from
`read_environ`, preventing `read_cgroup` from being called. As a result,
the `hypervisors` and `virtual` facts were often set incorrectly to
`container_other` and displayed a misleading warning.

Changes in this commit:
- `read_cgroup` now returns early unless Docker or LXC matches are found.
- `read_environ` returns `nil` when encountering an unsupported container.
- If both methods return `nil`, `vm` defaults to `container_other` with a warning.

These updates ensure that Facter correctly detects Docker and properly
reports the `virtual` and `hypervisors` facts when running inside a
Docker container.
  • Loading branch information
molhambnotk committed Jan 14, 2025
1 parent 0656d9a commit 07336b0
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions lib/facter/resolvers/containers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,17 @@ class << self

def post_resolve(fact_name, _options)
@fact_list.fetch(fact_name) do
read_environ(fact_name) || read_cgroup(fact_name)
environ_result = read_environ(fact_name)
cgroup_result = read_cgroup(fact_name)

if environ_result.nil? && cgroup_result.nil?
@fact_list[:vm] = 'container_other'
@fact_list[:hypervisor] = ''
log.warn("Container runtime is unsupported, setting to 'container_other'")
@fact_list[fact_name]
else
environ_result || cgroup_result
end
end
end

Expand All @@ -24,7 +34,8 @@ def read_cgroup(fact_name)
return unless output_cgroup

output_docker = %r{docker/(.+)}.match(output_cgroup)
output_lxc = %r{^/lxc/([^/]+)}.match(output_cgroup)
output_lxc = %r{^/lxc/([^/]+)}.match(output_cgroup)
return if output_docker.nil? && output_lxc.nil?

info, vm = extract_vm_and_info(output_docker, output_lxc)
@fact_list[:vm] = vm
Expand Down Expand Up @@ -57,8 +68,7 @@ def read_environ(fact_name)
vm = 'systemd_nspawn'
info = { 'id' => Facter::Util::FileHelper.safe_read('/etc/machine-id', nil).strip }
else
vm = 'container_other'
log.warn("Container runtime, '#{container}', is unsupported, setting to '#{vm}'")
return nil
end
@fact_list[:vm] = vm
@fact_list[:hypervisor] = { vm.to_sym => info } if vm
Expand Down

0 comments on commit 07336b0

Please sign in to comment.