Class: Puppet::Resource::Type

Inherits:
Object
  • Object
show all
Includes:
Util::Errors, Util::Warnings
Defined in:
lib/puppet/resource/type.rb

Overview

Puppet::Resource::Type represents nodes, classes and defined types.

Constant Summary collapse

RESOURCE_KINDS =
[:hostclass, :node, :definition, :capability_mapping, :application, :site]
RESOURCE_KINDS_TO_EXTERNAL_NAMES =

Map the names used in our documentation to the names used internally

{
    :hostclass => "class",
    :node => "node",
    :definition => "defined_type",
    :application => "application",
    :site => 'site'
}
RESOURCE_EXTERNAL_NAMES_TO_KINDS =
RESOURCE_KINDS_TO_EXTERNAL_NAMES.invert
NAME =
'name'.freeze
TITLE =
'title'.freeze
MODULE_NAME =
'module_name'.freeze
CALLER_MODULE_NAME =
'caller_module_name'.freeze
PARAMETERS =
'parameters'.freeze
KIND =
'kind'.freeze
NODES =
'nodes'.freeze
DOUBLE_COLON =
'::'.freeze
EMPTY_ARRAY =
[].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Util::Errors

#adderrorcontext, #devfail, #error_context, #exceptwrap, #fail

Methods included from Util::Warnings

clear_warnings, debug_once, notice_once, warnonce

Constructor Details

#initialize(type, name, options = {}) ⇒ Type

Returns a new instance of Type.

Raises:

  • (ArgumentError)


141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/puppet/resource/type.rb', line 141

def initialize(type, name, options = {})
  @type = type.to_s.downcase.to_sym
  raise ArgumentError, "Invalid resource supertype '#{type}'" unless RESOURCE_KINDS.include?(@type)

  name = convert_from_ast(name) if name.is_a?(Puppet::Parser::AST::HostName)

  set_name_and_namespace(name)

  [:code, :doc, :line, :file, :parent].each do |param|
    next unless value = options[param]
    send(param.to_s + '=', value)
  end

  set_arguments(options[:arguments])
  set_argument_types(options[:argument_types])

  @match = nil

  @module_name = options[:module_name]
end

Instance Attribute Details

#argument_typesHash<Symbol, Puppet::Pops::Types::PAnyType] map from name to type (readonly)

Map from argument (aka parameter) names to Puppet Type

Returns:



51
52
53
# File 'lib/puppet/resource/type.rb', line 51

def argument_types
  @argument_types
end

#argumentsObject (readonly)



37
38
39
# File 'lib/puppet/resource/type.rb', line 37

def arguments
  @arguments
end

#behaves_likeObject (readonly)



37
38
39
# File 'lib/puppet/resource/type.rb', line 37

def behaves_like
  @behaves_like
end

#codeObject



36
37
38
# File 'lib/puppet/resource/type.rb', line 36

def code
  @code
end

#docObject



36
37
38
# File 'lib/puppet/resource/type.rb', line 36

def doc
  @doc
end

#fileObject



36
37
38
# File 'lib/puppet/resource/type.rb', line 36

def file
  @file
end

#lineObject



36
37
38
# File 'lib/puppet/resource/type.rb', line 36

def line
  @line
end

#module_nameObject (readonly)



37
38
39
# File 'lib/puppet/resource/type.rb', line 37

def module_name
  @module_name
end

#namespaceObject (readonly)



37
38
39
# File 'lib/puppet/resource/type.rb', line 37

def namespace
  @namespace
end

#parentObject



36
37
38
# File 'lib/puppet/resource/type.rb', line 36

def parent
  @parent
end

#resource_type_collectionObject



36
37
38
# File 'lib/puppet/resource/type.rb', line 36

def resource_type_collection
  @resource_type_collection
end

#typeObject (readonly)

This should probably be renamed to ‘kind’ eventually, in accordance with the changes

made for serialization and API usability (#14137).  At the moment that seems like
it would touch a whole lot of places in the code, though.  --cprice 2012-04-23


56
57
58
# File 'lib/puppet/resource/type.rb', line 56

def type
  @type
end

Instance Method Details

#add_consumes(blueprint) ⇒ Object



175
176
177
178
# File 'lib/puppet/resource/type.rb', line 175

def add_consumes(blueprint)
  @consumes ||= []
  @consumes << blueprint
end

#add_produces(blueprint) ⇒ Object



170
171
172
173
# File 'lib/puppet/resource/type.rb', line 170

def add_produces(blueprint)
  @produces ||= []
  @produces << blueprint
end

#assign_parameter_values(parameters, resource) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deprecated.

Not used by Puppet



279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/puppet/resource/type.rb', line 279

def assign_parameter_values(parameters, resource)
  Puppet.deprecation_warning(_('The method Puppet::Resource::Type.assign_parameter_values is deprecated and will be removed in the next major release of Puppet.'))

  return unless parameters

  # It'd be nice to assign default parameter values here,
  # but we can't because they often rely on local variables
  # created during set_resource_parameters.
  parameters.each do |name, value|
    resource.set_parameter name, value
  end
end

#child_of?(klass) ⇒ Boolean

Are we a child of the passed class? Do a recursive search up our parentage tree to figure it out.

Returns:

  • (Boolean)


64
65
66
67
68
# File 'lib/puppet/resource/type.rb', line 64

def child_of?(klass)
  return false unless parent

  return(klass == parent_type ? true : parent_type.child_of?(klass))
end

#consumesObject



166
167
168
# File 'lib/puppet/resource/type.rb', line 166

def consumes
  @consumes || EMPTY_ARRAY
end

#ensure_in_catalog(scope, parameters = nil) ⇒ Object

Make an instance of the resource type, and place it in the catalog if it isn’t in the catalog already. This is only possible for classes and nodes. No parameters are be supplied–if this is a parameterized class, then all parameters take on their default values.



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
248
249
250
251
252
# File 'lib/puppet/resource/type.rb', line 222

def ensure_in_catalog(scope, parameters=nil)
  resource_type =
  case type
  when :definition
    raise ArgumentError, 'Cannot create resources for defined resource types'
  when :hostclass
    :class
  when :node
    :node
  when :site
    :site
  end

  # Do nothing if the resource already exists; this makes sure we don't
  # get multiple copies of the class resource, which helps provide the
  # singleton nature of classes.
  # we should not do this for classes with parameters
  # if parameters are passed, we should still try to create the resource
  # even if it exists so that we can fail
  # this prevents us from being able to combine param classes with include
  if parameters.nil?
    resource = scope.catalog.resource(resource_type, name)
    return resource unless resource.nil?
  elsif parameters.is_a?(Hash)
    parameters = parameters.map {|k, v| Puppet::Parser::Resource::Param.new(:name => k, :value => v, :source => self)}
  end
  resource = Puppet::Parser::Resource.new(resource_type, name, :scope => scope, :source => self, :parameters => parameters)
  instantiate_resource(scope, resource)
  scope.compiler.add_resource(scope, resource)
  resource
end

#evaluate_code(resource) ⇒ Object

Now evaluate the code associated with this class or definition.



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/puppet/resource/type.rb', line 115

def evaluate_code(resource)

  static_parent = evaluate_parent_type(resource)
  scope = static_parent || resource.scope

  scope = scope.newscope(:source => self, :resource => resource) unless resource.title == :main
  scope.compiler.add_class(name) unless definition?

  set_resource_parameters(resource, scope)

  resource.add_edge_to_stage

  evaluate_produces(resource, scope)

  if code
    if @match # Only bother setting up the ephemeral scope if there are match variables to add into it
      scope.with_guarded_scope do
        scope.ephemeral_from(@match, file, line)
        code.safeevaluate(scope)
      end
    else
      code.safeevaluate(scope)
    end
  end
end

#evaluate_produces(resource, scope) ⇒ Object

Evaluate the resources produced by the given resource. These resources are evaluated in a separate but identical scope from the rest of the resource.



72
73
74
75
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
# File 'lib/puppet/resource/type.rb', line 72

def evaluate_produces(resource, scope)
  # Only defined types and classes can produce capabilities
  return unless definition? || hostclass?

  resource.export.map do |ex|
    # Assert that the ref really is a resource reference
    raise Puppet::Error, _("Invalid export in %{reference}: %{ex} is not a resource") % { reference: resource.ref, ex: ex } unless ex.is_a?(Puppet::Resource)
    raise Puppet::Error, _("Invalid export in %{reference}: %{ex} is not a capability resource") % { reference: resource.ref, ex: ex } if ex.resource_type.nil? || !ex.resource_type.is_capability?

    blueprint = produces.find { |pr| pr[:capability] == ex.type }
    if blueprint.nil?
      raise Puppet::ParseError, _("Resource type %{res_type} does not produce %{ex_type}") % { res_type: resource.type, ex_type: ex.type }
    end
    t = ex.type
    t = Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_resource_type(scope, t) unless t == 'class' || t == 'node'
    produced_resource = Puppet::Parser::Resource.new(t, ex.title, :scope => scope, :source => self)

    produced_resource.resource_type.parameters.each do |name|
      next if name == :name

      if expr = blueprint[:mappings][name.to_s]
        produced_resource[name] = expr.safeevaluate(scope)
      else
        produced_resource[name] = scope[name.to_s]
      end
    end
    # Tag the produced resource so we can later distinguish it from
    # copies of the resource that wind up in the catalogs of nodes that
    # use this resource. We tag the resource with producer:<environment>,
    # meaning produced resources need to be unique within their
    # environment
    # @todo lutter 2014-11-13: we would really like to use a dedicated
    # metadata field to indicate the producer of a resource, but that
    # requires changes to PuppetDB and its API; so for now, we just use
    # tagging
    produced_resource.tag("producer:#{scope.catalog.environment}")
    scope.catalog.add_resource(produced_resource)
    produced_resource[:require] = resource.ref
    produced_resource
  end
end

#instantiate_resource(scope, resource) ⇒ Object



254
255
256
257
258
259
260
261
262
263
# File 'lib/puppet/resource/type.rb', line 254

def instantiate_resource(scope, resource)
  # Make sure our parent class has been evaluated, if we have one.
  if parent && !scope.catalog.resource(resource.type, parent)
    parent_type(scope).ensure_in_catalog(scope)
  end

  if ['Class', 'Node'].include? resource.type
    scope.catalog.tag(*resource.tags)
  end
end

#is_capability?Boolean

Returns boolean true if an instance of this type is a capability. This implementation always returns false. This “duck-typing” interface is shared among other classes and makes it easier to detect capabilities when they are intermixed with non capability instances.

Returns:

  • (Boolean)


436
437
438
# File 'lib/puppet/resource/type.rb', line 436

def is_capability?
  false
end

#match(string) ⇒ Object

This is only used for node names, and really only when the node name is a regexp.



182
183
184
185
186
# File 'lib/puppet/resource/type.rb', line 182

def match(string)
  return string.to_s.downcase == name unless name_is_regex?

  @match = @name.match(string)
end

#merge(other) ⇒ Object

Add code from a new instance to our code.



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
# File 'lib/puppet/resource/type.rb', line 189

def merge(other)
  fail _("%{name} is not a class; cannot add code to it") % { name: name } unless type == :hostclass
  fail _("%{name} is not a class; cannot add code from it") % { name: other.name } unless other.type == :hostclass
  fail _("Cannot have code outside of a class/node/define because 'freeze_main' is enabled") if name == "" and Puppet.settings[:freeze_main]

  if parent and other.parent and parent != other.parent
    fail _("Cannot merge classes with different parent classes (%{name} => %{parent} vs. %{other_name} => %{other_parent})") % { name: name, parent: parent, other_name: other.name, other_parent: other.parent }
  end

  # We know they're either equal or only one is set, so keep whichever parent is specified.
  self.parent ||= other.parent

  if other.doc
    self.doc ||= ""
    self.doc += other.doc
  end

  # This might just be an empty, stub class.
  return unless other.code

  unless self.code
    self.code = other.code
    return
  end

  self.code = Puppet::Parser::ParserFactory.code_merger.concatenate([self, other])
end

#nameObject



265
266
267
268
269
270
271
# File 'lib/puppet/resource/type.rb', line 265

def name
  if type == :node && name_is_regex?
    "__node_regexp__#{@name.source.downcase.gsub(/[^-\w:.]/,'').sub(/^\.+/,'')}"
  else
    @name
  end
end

#name_is_regex?Boolean

Returns:

  • (Boolean)


273
274
275
# File 'lib/puppet/resource/type.rb', line 273

def name_is_regex?
  @name.is_a?(Regexp)
end

#parent_type(scope = nil) ⇒ Object



292
293
294
295
296
297
# File 'lib/puppet/resource/type.rb', line 292

def parent_type(scope = nil)
  return nil unless parent

  @parent_type ||= scope.environment.known_resource_types.send("find_#{type}", parent) ||
    fail(Puppet::ParseError, _("Could not find parent resource type '%{parent}' of type %{parent_type} in %{env}") % { parent: parent, parent_type: type, env: scope.environment })
end

#producesObject



162
163
164
# File 'lib/puppet/resource/type.rb', line 162

def produces
  @produces || EMPTY_ARRAY
end

#set_argument_types(name_to_type_hash) ⇒ Object

Sets the argument name to Puppet Type hash used for type checking. Names must correspond to available arguments (they must be defined first). Arguments not mentioned will not be type-checked.



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/puppet/resource/type.rb', line 416

def set_argument_types(name_to_type_hash)
  @argument_types = {}
  @parameter_struct = nil
  return unless name_to_type_hash
  name_to_type_hash.each do |name, t|
    # catch internal errors
    unless @arguments.include?(name)
      raise Puppet::DevError, "Parameter '#{name}' is given a type, but is not a valid parameter."
    end
    unless t.is_a? Puppet::Pops::Types::PAnyType
      raise Puppet::DevError, "Parameter '#{name}' is given a type that is not a Puppet Type, got #{t.class}"
    end
    @argument_types[name] = t
  end
end

#set_arguments(arguments) ⇒ Object



400
401
402
403
404
405
406
407
408
409
410
# File 'lib/puppet/resource/type.rb', line 400

def set_arguments(arguments)
  @arguments = {}
  @parameter_struct = nil
  return if arguments.nil?

  arguments.each do |arg, default|
    arg = arg.to_s
    warn_if_metaparam(arg, default)
    @arguments[arg] = default
  end
end

#set_resource_parameters(resource, scope) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Validate and set any arguments passed by the resource as variables in the scope.

This method is known to only be used on the server/compile side.

Parameters:



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/puppet/resource/type.rb', line 307

def set_resource_parameters(resource, scope)
  # Inject parameters from using external lookup
  modname = resource[:module_name] || module_name
  scope[MODULE_NAME] = modname unless modname.nil?
  caller_name = resource[:caller_module_name] || scope.parent_module_name
  scope[CALLER_MODULE_NAME] = caller_name unless caller_name.nil?

  resource.add_parameters_from_consume
  inject_external_parameters(resource, scope)

  if @type == :hostclass
    scope[TITLE] = resource.title.to_s.downcase
    scope[NAME] =  resource.name.to_s.downcase
  else
    scope[TITLE] = resource.title
    scope[NAME] =  resource.name
  end
  scope.class_set(self.name,scope) if hostclass? || node?

  param_hash = scope.with_parameter_scope(resource.to_s, arguments.keys) do |param_scope|
    # Assign directly to the parameter scope to avoid scope parameter validation at this point. It
    # will happen anyway when the values are assigned to the scope after the parameter scoped has
    # been popped.
    resource.each { |k, v| param_scope[k.to_s] = v.value unless k == :name || k == :title }
    assign_defaults(resource, param_scope, scope)
    param_scope.to_hash
  end

  validate_resource_hash(resource, param_hash)

  # Assign parameter values to current scope
  param_hash.each { |param, value| exceptwrap { scope[param] = value }}
end

#valid_parameter?(param) ⇒ Boolean

Check whether a given argument is valid.

Returns:

  • (Boolean)


396
397
398
# File 'lib/puppet/resource/type.rb', line 396

def valid_parameter?(param)
  parameter_struct.hashed_elements.include?(param.to_s)
end

#validate_resource(resource) ⇒ Object

Validate that all parameters given to the resource are correct

Parameters:



383
384
385
386
387
388
389
390
391
392
393
# File 'lib/puppet/resource/type.rb', line 383

def validate_resource(resource)
  # Since Sensitive values have special encoding (in a separate parameter) an unwrapped sensitive value must be
  # recreated as a Sensitive in order to perform correct type checking.
  sensitives = Set.new(resource.sensitive_parameters)
  validate_resource_hash(resource,
    Hash[resource.parameters.map do |name, value|
      value_to_validate = sensitives.include?(name) ? Puppet::Pops::Types::PSensitiveType::Sensitive.new(value.value) : value.value
      [name.to_s, value_to_validate]
    end
  ])
end