/
relationship_validator.rb
56 lines (50 loc) · 1.79 KB
/
relationship_validator.rb
1
2
3
4
5
6
7
8
9
10
11
12
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Puppet::Parser::Compiler
# Validator that asserts that only 'require', 'consume', and 'export' is used when declaring relationships
# to capability resources.
class CatalogValidator::RelationshipValidator < CatalogValidator
def validate
catalog.resources.each do |resource|
next unless resource.is_a?(Puppet::Parser::Resource)
resource.eachparam do |param|
pclass = Puppet::Type.metaparamclass(param.name)
validate_relationship(param) if !pclass.nil? && pclass < Puppet::Type::RelationshipMetaparam
end
end
nil
end
private
# A hash lookup is 6x avg times faster than find among 3 values.
CAPABILITY_ACCEPTED_METAPARAMS = {:require => true, :consume => true, :export => true}.freeze
def validate_relationship(param)
# when relationship is to a capability
if has_capability?(param.value)
if ! CAPABILITY_ACCEPTED_METAPARAMS[param.name]
raise CatalogValidationError.new(
"'#{param.name}' is not a valid relationship to a capability",
param.file, param.line)
end
else
# all other relationships requires the referenced resource to exist
refs = param.value.is_a?(Array) ? param.value : [param.value]
refs.each do |r|
unless catalog.resource(r.to_s)
raise CatalogValidationError.new(
"Could not find resource '#{r.to_s}' in parameter '#{param.name.to_s}'",
param.file, param.line)
end
end
end
end
def has_capability?(value)
case value
when Array
value.find { |v| has_capability?(v) }
when Puppet::Resource
rt = value.resource_type
!rt.nil? && rt.is_capability?
else
false
end
end
end
end