Class: ComplianceEngine::Data

Inherits:
Object
  • Object
show all
Defined in:
lib/compliance_engine/data.rb

Overview

Work with compliance data

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*paths, facts: nil, enforcement_tolerance: nil) ⇒ Data

Returns a new instance of Data.

Parameters:

  • paths (Array<String>)

    The paths to the compliance data files

  • facts (Hash) (defaults to: nil)

    The facts to use while evaluating the data

  • enforcement_tolerance (Integer) (defaults to: nil)

    The tolerance to use while evaluating the data



30
31
32
33
34
35
# File 'lib/compliance_engine/data.rb', line 30

def initialize(*paths, facts: nil, enforcement_tolerance: nil)
  @data = {}
  @facts = facts
  @enforcement_tolerance = enforcement_tolerance
  open(*paths) unless paths.nil? || paths.empty?
end

Instance Attribute Details

#dataObject

Setting any of these should all invalidate any cached data



38
39
40
# File 'lib/compliance_engine/data.rb', line 38

def data
  @data
end

#enforcement_toleranceObject

Setting any of these should all invalidate any cached data



38
39
40
# File 'lib/compliance_engine/data.rb', line 38

def enforcement_tolerance
  @enforcement_tolerance
end

#environment_dataObject

Setting any of these should all invalidate any cached data



38
39
40
# File 'lib/compliance_engine/data.rb', line 38

def environment_data
  @environment_data
end

#factsObject

Setting any of these should all invalidate any cached data



38
39
40
# File 'lib/compliance_engine/data.rb', line 38

def facts
  @facts
end

#modulepathObject

Setting any of these should all invalidate any cached data



38
39
40
# File 'lib/compliance_engine/data.rb', line 38

def modulepath
  @modulepath
end

Instance Method Details

#cesComplianceEngine::CEs

Return a collection of CEs

Returns:

  • (ComplianceEngine::CEs)


278
279
280
# File 'lib/compliance_engine/data.rb', line 278

def ces
  @ces ||= ComplianceEngine::Ces.new(self)
end

#check_mapping(profile_or_ce) ⇒ Hash

Return all checks that map to the requested profile or CE

Parameters:

Returns:

  • (Hash)

Raises:

  • (ArgumentError)


362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/compliance_engine/data.rb', line 362

def check_mapping(profile_or_ce)
  raise ArgumentError, 'Argument must be a ComplianceEngine::Profile object' unless profile_or_ce.is_a?(ComplianceEngine::Profile) || profile_or_ce.is_a?(ComplianceEngine::Ce)

  cache_key = "#{profile_or_ce.class}:#{profile_or_ce.key}"

  @check_mapping ||= {}

  return @check_mapping[cache_key] if @check_mapping.key?(cache_key)

  @check_mapping[cache_key] = checks.select do |_, check|
    mapping?(check, profile_or_ce)
  end
end

#checksComplianceEngine::Checks

Return a collection of checks



285
286
287
# File 'lib/compliance_engine/data.rb', line 285

def checks
  @checks ||= ComplianceEngine::Checks.new(self)
end

#confinesHash

Return all confines

Returns:

  • (Hash)


299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/compliance_engine/data.rb', line 299

def confines
  return @confines unless @confines.nil?

  @confines ||= {}

  [profiles, ces, checks, controls].each do |collection|
    collection.each_value do |v|
      v.to_a.each do |component|
        next unless component.key?('confine')

        @confines = DeepMerge.deep_merge!(component['confine'], @confines)
      end
    end
  end

  @confines
end

#controlsComplianceEngine::Controls

Return a collection of controls



292
293
294
# File 'lib/compliance_engine/data.rb', line 292

def controls
  @controls ||= ComplianceEngine::Controls.new(self)
end

#filesArray<String>

Get a list of files with compliance data

Returns:

  • (Array<String>)


252
253
254
255
256
# File 'lib/compliance_engine/data.rb', line 252

def files
  return @files unless @files.nil?

  @files = data.select { |_, file| file.key?(:content) }.keys
end

#get(file) ⇒ Hash

Get the compliance data for a given file

Parameters:

  • file (String)

    The path to the compliance data file

Returns:

  • (Hash)


262
263
264
265
266
# File 'lib/compliance_engine/data.rb', line 262

def get(file)
  data[file][:content]
rescue StandardError
  nil
end

#hiera(requested_profiles = []) ⇒ Hash

Return all Hiera data from checks that map to the requested profiles

Parameters:

  • requested_profiles (Array<String>) (defaults to: [])

    The requested profiles

Returns:

  • (Hash)


321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/compliance_engine/data.rb', line 321

def hiera(requested_profiles = [])
  # If we have no valid profiles, we won't have any hiera data.
  return {} if requested_profiles.empty?

  cache_key = requested_profiles.to_s

  @hiera ||= {}

  return @hiera[cache_key] if @hiera.key?(cache_key)

  valid_profiles = []
  requested_profiles.each do |profile|
    if profiles[profile].nil?
      ComplianceEngine.log.error "Requested profile '#{profile}' not defined"
      next
    end

    valid_profiles << profiles[profile]
  end

  # If we have no valid profiles, we won't have any hiera data.
  if valid_profiles.empty?
    @hiera[cache_key] = {}
    return @hiera[cache_key]
  end

  parameters = {}

  valid_profiles.reverse_each do |profile|
    check_mapping(profile).each_value do |check|
      parameters = DeepMerge.deep_merge!(check.hiera, parameters)
    end
  end

  @hiera[cache_key] = parameters
end

#initialize_copy(_source) ⇒ NilClass

Ensure that cloned/duped objects get independent collection instances.

Ruby’s default clone/dup is a shallow copy, so the collection instance variables (@ces, @profiles, @checks, @controls) would otherwise point to the same objects as the source. When facts= is later called on either the source or the clone, invalidate_cache propagates facts into the shared collection, causing the other object to silently adopt the wrong facts.

Nilling the collection variables here forces each clone to lazily rebuild its own collections the first time they are accessed, using its own context (facts, enforcement_tolerance, etc.). Cache variables that depend on those collections are cleared for the same reason.

Returns:

  • (NilClass)


105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/compliance_engine/data.rb', line 105

def initialize_copy(_source)
  super
  # Give each clone its own outer @data hash and its own per-file inner
  # hashes so that new files opened on one clone (via open/update) are not
  # visible to other clones or the source, and so that a loader refresh on
  # the source (which mutates the inner hash in-place via Data#update) does
  # not silently affect a clone that has not yet built its lazy collections.
  # The inner per-file content values (read-only parsed data) stay shared.
  #
  # :loader is additionally cleared (set to nil) so the copy does not hold
  # a reference to the source's DataLoader object.  If it did, the copy
  # calling update(key_string) for an already-known file would invoke
  # loader.refresh, which notifies the source (the registered Observable
  # observer) and overwrites source.data[key][:content] while the copy's
  # inner hash stays stale.  With :loader nil the copy creates its own
  # independent loader (and registers itself as observer) on next access.
  @data = @data.transform_values { |entry| entry.merge(loader: nil) }
  collection_variables.each { |var| instance_variable_set(var, nil) }
  cache_variables.each { |var| instance_variable_set(var, nil) }
  nil
end

#invalidate_cacheNilClass

Invalidate the cache of computed data

Returns:

  • (NilClass)


78
79
80
81
# File 'lib/compliance_engine/data.rb', line 78

def invalidate_cache
  collection_variables.each { |var| instance_variable_get(var)&.invalidate_cache(self) }
  cache_variables.each { |var| instance_variable_set(var, nil) }
end

#open(*paths, fileclass: File, dirclass: Dir) ⇒ NilClass

Scan paths for compliance data files

Parameters:

  • paths (Array<String>)

    The paths to the compliance data files

  • fileclass (Class) (defaults to: File)

    The class to use for reading files

  • dirclass (Class) (defaults to: Dir)

    The class to use for reading directories

Returns:

  • (NilClass)


153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/compliance_engine/data.rb', line 153

def open(*paths, fileclass: File, dirclass: Dir)
  modules = {}

  paths.each do |path|
    if path.is_a?(ComplianceEngine::EnvironmentLoader)
      open(*path.modules)
      next
    end

    if path.is_a?(ComplianceEngine::ModuleLoader)
      modules[path.name] = path.version unless path.name.nil?
      path.files.each do |file_loader|
        update(file_loader)
      end
      next
    end

    if path.is_a?(ComplianceEngine::DataLoader)
      update(path, key: path.key, fileclass: fileclass)
      next
    end

    if fileclass.file?(path)
      update(path, key: path.to_s, fileclass: fileclass)
      next
    end

    if fileclass.directory?(path)
      open(ComplianceEngine::ModuleLoader.new(path, fileclass: fileclass, dirclass: dirclass))
      next
    end

    raise ComplianceEngine::Error, "Invalid path or object '#{path}'"
  end

  self.environment_data ||= {}
  self.environment_data = self.environment_data.merge(modules)

  nil
end

#open_environment(*paths) ⇒ NilClass

Scan a Puppet environment

Parameters:

  • paths (Array<String>)

    The Puppet modulepath components

Returns:

  • (NilClass)


141
142
143
144
145
# File 'lib/compliance_engine/data.rb', line 141

def open_environment(*paths)
  environment = ComplianceEngine::EnvironmentLoader.new(*paths)
  self.modulepath = environment.modulepath
  open(environment)
end

#open_environment_zip(path) ⇒ NilClass

Scan a Puppet environment from a zip file

Parameters:

  • path (String)

    The Puppet environment archive file

Returns:

  • (NilClass)


130
131
132
133
134
135
136
# File 'lib/compliance_engine/data.rb', line 130

def open_environment_zip(path)
  require 'compliance_engine/environment_loader/zip'

  environment = ComplianceEngine::EnvironmentLoader::Zip.new(path)
  self.modulepath = environment.modulepath
  open(environment)
end

#profilesComplianceEngine::Profiles

Return a profile collection



271
272
273
# File 'lib/compliance_engine/data.rb', line 271

def profiles
  @profiles ||= ComplianceEngine::Profiles.new(self)
end

#reset_collectionNilClass

Discard all parsed data other than the top-level data

Returns:

  • (NilClass)


86
87
88
89
# File 'lib/compliance_engine/data.rb', line 86

def reset_collection
  # Discard any cached objects
  (instance_variables - (data_variables + context_variables)).each { |var| instance_variable_set(var, nil) }
end

#update(filename, key: filename.to_s, fileclass: File) ⇒ NilClass

Update the data for a given file

Parameters:

  • file (String)

    The path to the compliance data file

  • key (String) (defaults to: filename.to_s)

    The key to use for the data

  • fileclass (Class) (defaults to: File)

    The class to use for reading files

  • size (Integer)

    The size of the file

  • mtime (Time)

    The modification time of the file

Returns:

  • (NilClass)


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
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/compliance_engine/data.rb', line 202

def update(
  filename,
  key: filename.to_s,
  fileclass: File
)
  if filename.is_a?(String)
    data[key] ||= {}

    if data[key]&.key?(:loader) && data[key][:loader]
      data[key][:loader].refresh if data[key][:loader].respond_to?(:refresh)
      return
    end

    loader = if File.extname(filename) == '.json'
               ComplianceEngine::DataLoader::Json.new(filename, fileclass: fileclass, key: key)
             else
               ComplianceEngine::DataLoader::Yaml.new(filename, fileclass: fileclass, key: key)
             end

    loader.add_observer(self, :update)
    data[key] = {
      loader: loader,
      version: ComplianceEngine::Version.new(loader.data['version']),
      content: loader.data,
    }
  else
    data[filename.key] ||= {}

    # Register as an observer only when no loader is currently attached.
    # Checking the :loader value (rather than key presence) is important
    # after clone/dup: initialize_copy sets :loader to nil so the copy does
    # not share the source's loader, but the key still exists.  Checking
    # key presence would see the nil as "already registered" and skip
    # add_observer, leaving the copy deaf to future loader refreshes.
    unless data[filename.key][:loader]
      data[filename.key][:loader] = filename
      data[filename.key][:loader].add_observer(self, :update)
    end
    data[filename.key][:version] = ComplianceEngine::Version.new(filename.data['version'])
    data[filename.key][:content] = filename.data
  end

  reset_collection
rescue StandardError => e
  ComplianceEngine.log.error e.message
end