Module: Simp::RspecPuppetFacts

Defined in:
lib/simp/rspec-puppet-facts.rb,
lib/simp/version.rb

Overview

Simp::RspecPuppetFacts namespace

Defined Under Namespace

Classes: Shim

Constant Summary collapse

VERSION =
'4.0.1'.freeze
SELINUX_MODES =
[:enforcing, :disabled, :permissive].freeze

Instance Method Summary collapse

Instance Method Details

#filter_opts(opts, simp_h) ⇒ Object

Don't ask rspec-puppet-facts for operatingsystems we've already recorded because if it doesn't have them it will crash



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/simp/rspec-puppet-facts.rb', line 44

def filter_opts(opts, simp_h)
  rfh_hw = opts.fetch(:hardwaremodels, ['x86_64'])
  rfh_os = opts.fetch(:supported_os) { RspecPuppetFacts.meta_supported_os }.dup

  filtered_opts = []
  rfh_os.each do |os|
    os['operatingsystemrelease'] ||= []
    if os['operatingsystemrelease'].empty?
      os_release = simp_h.keys
                         .select { |x| x.start_with?(os['operatingsystem'].downcase) }
                         .sort
                         .last

      os['operatingsystemrelease'] = [os_release.split('-')[1]] if os_release
    end

    next if os['operatingsystemrelease'].empty?

    # Only pass along the releases we don't have facts for, and only list
    # each OS once, no matter how many of its releases are missing
    missing_releases = os['operatingsystemrelease'].select do |rel|
      rfh_hw.any? { |hw| !simp_h.key?([os['operatingsystem'].downcase, rel, hw].join('-')) }
    end

    filtered_opts.push(os.merge('operatingsystemrelease' => missing_releases)) unless missing_releases.empty?
  end

  ret_opts = opts.dup
  ret_opts[:supported_os] = filtered_opts
  ret_opts
end

#load_facts(fact_dir_path) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/simp/rspec-puppet-facts.rb', line 191

def load_facts(fact_dir_path)
  facter_xy_version = Facter.version.split('.')[0..1].join('.')
  fact_dir          = File.join(fact_dir_path, facter_xy_version)

  unless File.exist? fact_dir
    # Try to fall back to the highest available older version
    available_versions = Dir.glob(File.join(fact_dir_path, '*'))
                            .select { |d| File.directory?(d) }
                            .map { |d| File.basename(d) }
                            .select { |v| v.match?(%r{^\d+\.\d+$}) }
                            .sort_by { |v| Gem::Version.new(v) }
                            .reverse

    fallback_version = available_versions.find do |v|
      Gem::Version.new(v) < Gem::Version.new(facter_xy_version)
    end

    if fallback_version
      fact_dir = File.join(fact_dir_path, fallback_version)
      warn "WARNING: No SIMP factsets for Facter #{facter_xy_version}; " \
           "falling back to the newest available factsets (Facter #{fallback_version})"
    else
      msg = <<~END_MSG
        Can't find SIMP facts for Facter #{facter_xy_version}, skipping...

        HINT: If this version of Facter has been released recently, try running

            `FACTER_GEM_VERSION='~> X.Y.0' bundler update facter

        Where 'X.Y' is the version of the last facter that worked
      END_MSG
      raise(msg)
    end
  end

  simp_h     = {}
  fact_files = Dir.glob(File.join(fact_dir, '*.facts')).sort
  fact_files.each do |file|
    key  = File.basename(file).sub(%r{\.facts$}, '')
    data = JSON.parse(File.read(file))
    simp_h[key] = symbolize_keys(data)
  end
  simp_h
end

#lsb_facts(facts) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
# File 'lib/simp/rspec-puppet-facts.rb', line 119

def lsb_facts(facts)
  return facts unless facts[:kernel].casecmp('linux')

  lsb_facts = {}
  # attempt to massage a major release version if missing (for facter 1.6)
  unless ENV['SIMP_FACTS_lsb'] == 'no'
    puts '==== mocking lsb facts [disable with SIMP_FACTS_lsb=no]' if ENV['VERBOSE']
    lsb_facts[:lsbmajdistrelease] = facts[:os][:release][:major]
  end
  lsb_facts
end

#on_supported_os(opts = {}) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/simp/rspec-puppet-facts.rb', line 76

def on_supported_os(opts = {})
  opts[:simp_fact_dir_path] ||= File.expand_path('../../facts/', File.dirname(__FILE__))

  simp_h = load_facts(opts[:simp_fact_dir_path])

  masked_opts = filter_opts(opts, simp_h)
  Simp::RspecPuppetFacts::Shim.on_supported_os(masked_opts) unless masked_opts[:supported_os]&.empty?

  # merged_os_hash = rfh_h.merge(simp_h)  # we should NOT merge default facterdb factsets
  merged_os_hash = simp_h
  h = merged_os_hash.slice(*supported_os_strings(opts, merged_os_hash.keys))

  h.each do |os, facts|
    facter_ver = Facter.version.split('.')[0..1].join('.')
    facts_file = File.expand_path("../../facts/#{facter_ver}/#{os}.facts",
                                  File.dirname(__FILE__))
    if File.file? facts_file
      captured_facts_raw = File.open(
        File.expand_path("../../facts/#{facter_ver}/#{os}.facts",
                         File.dirname(__FILE__)),
      ).read
      captured_facts = symbolize_keys JSON.parse(captured_facts_raw)
      captured_facts.keep_if { |k, _v| (captured_facts.keys - facts.keys).include? k }

      facts.merge! captured_facts
      facts.merge! opts.fetch(:extra_facts, {})
      facts[:puppetversion] = ::Puppet.version
      facts.merge! lsb_facts(facts)
      facts.merge! selinux_facts(opts[:selinux_mode], facts)
      facts.merge! opts.fetch(:extra_facts_immutable, {})
    end

    next unless ENV['SIMP_FACTS_OS'] &&
                !ENV['SIMP_FACTS_OS'].to_s.strip.empty? &&
                ENV['SIMP_FACTS_OS'] !~ %r{all}i
    unless ENV['SIMP_FACTS_OS'].strip.split(%r{[ ,]+}).any? { |str| os == str || os.match?(%r{#{str}}) }
      h.delete(os)
    end
  end

  h
end

#selinux_facts(mode = :enforcing, facts) ⇒ Object

rubocop:disable Style/OptionalArguments



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/simp/rspec-puppet-facts.rb', line 131

def selinux_facts(mode = :enforcing, facts) # rubocop:disable Style/OptionalArguments
  return facts if facts[:kernel]&.casecmp('windows')

  unless SELINUX_MODES.include?(mode)
    raise "FATAL: `mode` must be one of: #{SELINUX_MODES.map { |x| x.to_s.sub(%r{^}, ':') }.join(', ')}"
  end
  sefacts_enforcing = {
    selinux: true,
    selinux_enforced: true,
    selinux_current_mode: 'enforcing',
    selinux_state: 'enforcing',
  }
  sefacts_permissive = {
    selinux: true,
    selinux_enforced: false,
    selinux_current_mode: 'permissive',
    selinux_state: 'permssive',
  }
  sefacts_disabled = {
    selinux: false,
    selinux_enforced: false,
    selinux_current_mode: 'disabled',
    selinux_state: 'disabled',
  }
  sefacts = sefacts_enforcing
  sefacts = sefacts_enforcing  if mode == :enforcing
  sefacts = sefacts_permissive if mode == :permissive
  sefacts = sefacts_disabled   if mode == :disabled

  # ensure mount options in :tmp_mount_* facts match
  ['tmp', 'var_tmp', 'dev_shm'].each do |m|
    k = "tmp_mount_#{m}".to_sym
    if (mount_opts = facts.fetch(k, false))
      if mode == :disabled
        sefacts[k] = mount_opts.sub(%r{,seclabel$|seclabel,}, '')
      else
        unless %r{\bseclabel\b}.match?(mount_opts)
          sefacts[k] = "#{mount_opts},seclabel"
        end
      end
    end
  end
  facts.merge sefacts
end

#supported_os_strings(opts, known_os_list = []) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/simp/rspec-puppet-facts.rb', line 13

def supported_os_strings(opts, known_os_list = [])
  # The default has to be a block so that metadata.json is only consulted
  # when :supported_os wasn't given
  supported_os = opts.fetch(:supported_os) { RspecPuppetFacts.meta_supported_os }
  hardwaremodels = opts.fetch(:hardwaremodels, ['x86_64'])
  os_strings = []
  supported_os.each do |os|
    os_name = os['operatingsystem'].downcase.gsub(%r{\s}, '_')

    os['operatingsystemrelease'] ||= []
    if os['operatingsystemrelease'].empty?
      # Just pick the latest one
      os_strings.push(
        known_os_list
          .select { |x| x.start_with?(os_name) }
          .sort.last,
      )
    else
      os['operatingsystemrelease'].each do |rel|
        hardwaremodels.each do |hw|
          os_strings.push([os_name, rel, hw].join('-'))
        end
      end
    end
  end

  os_strings.compact
end

#symbolize_keys(hash) ⇒ Object

recursively onvert all hash keys to symbols



177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/simp/rspec-puppet-facts.rb', line 177

def symbolize_keys(hash)
  hash.each_with_object({}) do |(key, value), result|
    new_key = case key
              when String then key.to_sym
              else key
              end
    new_value = case value
                when Hash then symbolize_keys(value)
                else value
                end
    result[new_key] = new_value
  end
end