Facter.add(:libvirt_activedomains) do
    confine :kernel => :linux
    setcode do
        begin
            require 'libvirt'
            conn = Libvirt::open_read_only('qemu:///system')
            doms = Array.new
            conn.list_domains.each do |domid|
                dom = conn.lookup_domain_by_id(domid)
                doms << dom.name
            end
            conn.close
            doms.sort.join(',')
        rescue LoadError
            Facter.debug('ruby-libvirt not available')
        rescue Libvirt::ConnectionError
            Facter.debug('libvirt connection failed')
        end
    end
end

Facter.add(:libvirt_inactivedomains) do
    confine :kernel => :linux
    setcode do
        begin
            require 'libvirt'
            conn = Libvirt::open_read_only('qemu:///system')
            doms = Array.new
            conn.list_defined_domains.each do |domname|
                doms << domname
            end
            conn.close
            doms.sort.join(',')
        rescue LoadError
            Facter.debug('ruby-libvirt not available')
        rescue Libvirt::ConnectionError
            Facter.debug('libvirt connection failed')
        end
    end
end

Facter.add(:libvirt_memorysize) do
    confine :kernel => :linux
    setcode do
        begin
            require 'libvirt'
            conn = Libvirt::open_read_only('qemu:///system')
            val = 0
            conn.list_domains.each do |domid|
                dom = conn.lookup_domain_by_id(domid)
                val += dom.max_memory
            end
            conn.close
            Facter::Memory.scale_number(val.to_f, "kB")
        rescue LoadError
            Facter.debug('ruby-libvirt not available')
        rescue Libvirt::ConnectionError
            Facter.debug('libvirt connection failed')
        end
    end
end

Facter.add(:libvirt_processorcount) do
    confine :kernel => :linux
    setcode do
        begin
            require 'libvirt'
            conn = Libvirt::open_read_only('qemu:///system')
            val = 0
            conn.list_domains.each do |domid|
                dom = conn.lookup_domain_by_id(domid)
                val += dom.max_vcpus
            end
            conn.close
            val.to_s
        rescue LoadError
            Facter.debug('ruby-libvirt not available')
        rescue Libvirt::ConnectionError
            Facter.debug('libvirt connection failed')
        end
    end
end
