Skip to content

Commit 47a729a

Browse files
committed
(FACT-3433) Log error if external fact is invalid
Prior to this commit, when Facter attempted to load an external fact that used a non-hash data type, it would cause a fatal exception. This commit updates Facter to validate whether an external fact is a non-empty hash and, if it isn't, logs an error. This brings Facter 4 behavior more in line with Facter 3. This commit also updates the debug message for structured data facts that are the wrong filetype or empty to provide more useful debug information.
1 parent 81045e8 commit 47a729a

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

lib/facter/custom_facts/util/directory_loader.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,12 @@ def load_searched_facts(collection, searched_facts, weight)
9393
if data == false
9494
log.warn "Could not interpret fact file #{fact.file}"
9595
elsif (data == {}) || data.nil?
96-
log.debug("Fact file #{fact.file} was parsed but no key=>value data was returned")
96+
log.debug(
97+
"Structured data fact file #{fact.file} was parsed but was either empty or an invalid filetype "\
98+
'(valid filetypes are .yaml, .json, and .txt).'
99+
)
100+
elsif !data.is_a?(Hash)
101+
log.error("Structured data fact file #{fact.file} was parsed but no key=>value data was returned.")
97102
else
98103
add_data(data, collection, fact, weight)
99104
end

spec/custom_facts/util/directory_loader_spec.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,31 @@
4646
expect(collection_double).to have_received(:add).with('f1', value: 'one', fact_type: :external, file: file)
4747
end
4848

49+
it 'ignores when a structured data fact contains empty hash' do
50+
data = {}
51+
write_to_file('data.yaml', YAML.dump(data))
52+
file = File.join(dir_loader.directories[0], 'data.yaml')
53+
54+
expect(log_spy).to receive(:debug).with(
55+
"Structured data fact file #{file} was parsed but was either empty or an invalid filetype (valid filetypes "\
56+
'are .yaml, .json, and .txt).'
57+
)
58+
59+
dir_loader.load(collection)
60+
end
61+
62+
it 'ignores when fact with external type contains invalid data type' do
63+
data = 'foo'
64+
write_to_file('data.yaml', YAML.dump(data))
65+
file = File.join(dir_loader.directories[0], 'data.yaml')
66+
67+
expect(log_spy).to receive(:error).with(
68+
"Structured data fact file #{file} was parsed but no key=>value data was returned."
69+
)
70+
71+
dir_loader.load(collection)
72+
end
73+
4974
it "ignores files that begin with '.'" do
5075
not_to_be_used_collection = double('collection should not be used')
5176
expect(not_to_be_used_collection).not_to receive(:add)

0 commit comments

Comments
 (0)