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



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

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



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

def data
  @data
end

#enforcement_toleranceObject

Setting any of these should all invalidate any cached data



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

def enforcement_tolerance
  @enforcement_tolerance
end

#environment_dataObject

Setting any of these should all invalidate any cached data



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

def environment_data
  @environment_data
end

#factsObject

Setting any of these should all invalidate any cached data



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

def facts
  @facts
end

#modulepathObject

Setting any of these should all invalidate any cached data



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

def modulepath
  @modulepath
end

Instance Method Details

#cesComplianceEngine::CEs

Return a collection of CEs

Returns:

  • (ComplianceEngine::CEs)


303
304
305
# File 'lib/compliance_engine/data.rb', line 303

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)


402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/compliance_engine/data.rb', line 402

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



310
311
312
# File 'lib/compliance_engine/data.rb', line 310

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

#confinesHash

Return all confines

Returns:

  • (Hash)


324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/compliance_engine/data.rb', line 324

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')

        confine = component['confine'].transform_values { |val| val.is_a?(Array) ? val.dup : Array(val) }
        @confines = DeepMerge.deep_merge!(confine, @confines, knockout_prefix: '--')
      end
    end
  end

  @confines
end

#controlsComplianceEngine::Controls

Return a collection of controls



317
318
319
# File 'lib/compliance_engine/data.rb', line 317

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

#filesArray<String>

Get a list of files with compliance data

Returns:

  • (Array<String>)


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

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)


287
288
289
290
291
# File 'lib/compliance_engine/data.rb', line 287

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)


347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/compliance_engine/data.rb', line 347

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|
      hiera_data = check.hiera
      next if hiera_data.nil?

      parameters = DeepMerge.deep_merge!(Marshal.load(Marshal.dump(hiera_data)), parameters)
    end
  end

  # deep_merge does not support hash-key knockout via knockout_prefix.
  # Handle parameter-name knockout explicitly: any key starting with '--'
  # signals that the matching key without the prefix should be suppressed
  # (mirrors compliance_markup behavior).
  parameters.each_key do |key|
    next unless key.start_with?('--')

    parameters.delete(key.delete_prefix('--'))
    parameters.delete(key)
  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)


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

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)


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

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)


170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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
# File 'lib/compliance_engine/data.rb', line 170

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?
      new_keys = path.files.to_set(&:key)
      module_root = if path.zipfile_path
                      ::File.join(path.zipfile_path, '.', path.path.sub(%r{^/+}, ''))
                    else
                      path.path
                    end
      module_prefix = ::File.join(module_root, '')
      stale_keys = data.keys.select { |k| (k == module_root || k.start_with?(module_prefix)) && !new_keys.include?(k) }
      stale_keys.each { |k| data.delete(k) }
      path.files.each { |file_loader| update(file_loader) }
      reset_collection if path.files.empty? && !stale_keys.empty?
      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)


158
159
160
161
162
# File 'lib/compliance_engine/data.rb', line 158

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

#open_environment_zip(path, name: nil) ⇒ NilClass

Scan a Puppet environment from a zip file on disk

Parameters:

  • path (String)

    filesystem path to the zip archive

  • name (String, nil) (defaults to: nil)

    stable string identifier used as the modulepath and cache-key prefix; defaults to the full path string passed as path.

Returns:

  • (NilClass)


133
134
135
136
137
138
139
# File 'lib/compliance_engine/data.rb', line 133

def open_environment_zip(path, name: nil)
  require 'compliance_engine/environment_loader/zip'

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

#open_environment_zip_bytes(bytes, name: nil) ⇒ NilClass

Scan a Puppet environment from a raw zip byte string

Parameters:

  • bytes (String)

    raw binary zip data (e.g. from File.binread or an HTTP body)

  • name (String, nil) (defaults to: nil)

    stable string identifier used as the modulepath and cache-key prefix; defaults to “-” when no filename is available.

Returns:

  • (NilClass)


147
148
149
150
151
152
153
# File 'lib/compliance_engine/data.rb', line 147

def open_environment_zip_bytes(bytes, name: nil)
  require 'compliance_engine/environment_loader/zip_bytes'

  environment = ComplianceEngine::EnvironmentLoader::ZipBytes.new(bytes, name: name)
  self.modulepath = environment.modulepath
  open(environment)
end

#profilesComplianceEngine::Profiles

Return a profile collection



296
297
298
# File 'lib/compliance_engine/data.rb', line 296

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

#reset_collectionNilClass

Discard all parsed data other than the top-level data

Returns:

  • (NilClass)


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

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)


227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/compliance_engine/data.rb', line 227

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::DataVersion.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::DataVersion.new(filename.data['version'])
    data[filename.key][:content] = filename.data
  end

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