diff --git a/modules/incus/lib/facter/incus_facts.rb b/modules/incus/lib/facter/incus_facts.rb new file mode 100644 index 0000000..0ac9eb1 --- /dev/null +++ b/modules/incus/lib/facter/incus_facts.rb @@ -0,0 +1,70 @@ +# frozen_string_literal: true + +require 'json' + +Facter::Util::Resolution.define_singleton_method(:incus_data) do + raw = Facter::Util::Resolution.exec('incus list --format=json') + return [] unless raw + + JSON.parse(raw) +rescue StandardError + [] +end + +Facter.add(:incus_container_count) do + confine kernel: 'Linux' + setcode do + Facter::Util::Resolution.incus_data.size + end +end + +Facter.add(:incus_container_count_running) do + confine kernel: 'Linux' + setcode do + Facter::Util::Resolution.incus_data.count { |c| c['status'] == 'Running' } + end +end + +Facter.add(:incus_allocated_mb) do + confine kernel: 'Linux' + setcode do + Facter::Util::Resolution.incus_data.sum do |c| + mem_str = c.dig('expanded_config', 'limits.memory') + if mem_str&.match(/^(\d+)(MB|GB)$/i) + value = Regexp.last_match(1).to_i + unit = Regexp.last_match(2).upcase + unit == 'GB' ? value * 1024 : value + else + 0 + end + end + end +end + +Facter.add(:incus_allocated_cpu) do + confine kernel: 'Linux' + setcode do + Facter::Util::Resolution.incus_data.sum do |c| + cpu_str = c.dig('expanded_config', 'limits.cpu') + cpu_str ? cpu_str.to_i : 0 + end + end +end + +Facter.add(:incus_profile_names) do + confine kernel: 'Linux' + setcode do + Facter::Util::Resolution.incus_data.flat_map { |c| c['profiles'] }.uniq.sort + end +end + +Facter.add(:incus_profile_usage_count) do + confine kernel: 'Linux' + setcode do + usage = Hash.new(0) + Facter::Util::Resolution.incus_data.each do |c| + c['profiles'].each { |profile| usage[profile] += 1 } + end + usage + end +end