Class: Puppet::Parser::Resource

Inherits:
Resource show all
Includes:
Util, Util::Errors, Util::Logging, Util::MethodHelper
Defined in:
lib/puppet/parser/resource.rb

Overview

The primary difference between this class and its parent is that this class has rules on who can set parameters

Defined Under Namespace

Classes: Param

Constant Summary

Constants included from Util::Logging

Util::Logging::FILE_AND_LINE, Util::Logging::FILE_NO_LINE, Util::Logging::MM, Util::Logging::NO_FILE_LINE, Util::Logging::SUPPRESS_FILE_LINE

Constants included from Util

Util::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE

Constants included from Util::POSIX

Util::POSIX::LOCALE_ENV_VARS, Util::POSIX::USER_ENV_VARS

Constants included from Util::SymbolicFileMode

Util::SymbolicFileMode::SetGIDBit, Util::SymbolicFileMode::SetUIDBit, Util::SymbolicFileMode::StickyBit, Util::SymbolicFileMode::SymbolicMode, Util::SymbolicFileMode::SymbolicSpecialToBit

Constants inherited from Resource

Resource::ATTRIBUTES, Resource::EMPTY_ARRAY, Resource::EMPTY_HASH, Resource::PCORE_TYPE_KEY, Resource::TYPE_CLASS, Resource::TYPE_NODE, Resource::TYPE_SITE, Resource::VALUE_KEY

Constants included from Indirector

Indirector::BadNameRegexp

Constants included from Util::Tagging

Util::Tagging::ValidTagRegex

Instance Attribute Summary collapse

Attributes inherited from Resource

#rich_data_enabled, #sensitive_parameters, #strict, #title, #type, #validate_parameters

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util::Logging

#clear_deprecation_warnings, #debug, #deprecation_warning, #format_exception, #get_deprecation_offender, #log_and_raise, #log_deprecations_to_file, #log_exception, #puppet_deprecation_warning, #send_log, setup_facter_logging!, #warn_once

Methods included from Util::Errors

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

Methods included from Util::MethodHelper

#requiredopts, #set_options, #symbolize_options

Methods included from Util

absolute_path?, benchmark, chuser, clear_environment, default_env, deterministic_rand, deterministic_rand_int, exit_on_fail, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, safe_posix_fork, set_env, symbolizehash, thinmark, uri_encode, uri_query_encode, uri_to_path, which, withenv, withumask

Methods included from Util::POSIX

#get_posix_field, #gid, #idfield, #methodbyid, #methodbyname, #search_posix_field, #uid

Methods included from Util::SymbolicFileMode

#normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Methods inherited from Resource

#==, #builtin?, #builtin_type?, #class?, #copy_as_resource, #each, #environment=, #export, from_data_hash, #include?, #initialize_from_hash, #inspect, #is_application_component?, #is_capability?, #key_attributes, #prune_parameters, #ref, #resolve, resource_type, #resource_type, #resource_type=, #set_default_parameters, #stage?, #to_data_hash, #to_hierayaml, #to_manifest, #to_ref, #to_s, type_and_title, #uniqueness_key, #valid_parameter?, #validate_complete, #validate_parameter, value_to_json_data, #yaml_property_munge

Methods included from Indirector

configure_routes, #indirects

Methods included from Enumerable

#uniq

Methods included from Util::PsychSupport

#encode_with, #init_with

Methods included from Util::Tagging

#merge_into, #merge_tags, #set_tags, #tag, #tag_if_valid, #tagged?, #tags, #tags=

Constructor Details

#initialize(type, title, attributes, with_defaults = true) ⇒ Resource

Returns a new instance of Resource.

Raises:

  • (ArgumentError)


124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/puppet/parser/resource.rb', line 124

def initialize(type, title, attributes, with_defaults = true)
  raise ArgumentError, _('Resources require a hash as last argument') unless attributes.is_a? Hash
  raise ArgumentError, _('Resources require a scope') unless attributes[:scope]
  super(type, title, attributes)

  @source ||= scope.source

  if with_defaults
    scope.lookupdefaults(self.type).each_pair do |name, param|
      unless @parameters.include?(name)
        self.debug "Adding default for #{name}"

        param = param.dup
        @parameters[name] = param
        tag(*param.value) if param.name == :tag
      end
    end
  end
end

Instance Attribute Details

#catalogObject

Returns the value of attribute catalog.



16
17
18
# File 'lib/puppet/parser/resource.rb', line 16

def catalog
  @catalog
end

#collector_idObject

Returns the value of attribute collector_id.



15
16
17
# File 'lib/puppet/parser/resource.rb', line 15

def collector_id
  @collector_id
end

#evaluatedObject

Returns the value of attribute evaluated.



16
17
18
# File 'lib/puppet/parser/resource.rb', line 16

def evaluated
  @evaluated
end

#exportedObject

Returns the value of attribute exported.



19
20
21
# File 'lib/puppet/parser/resource.rb', line 19

def exported
  @exported
end

#fileObject

Returns the value of attribute file.



17
18
19
# File 'lib/puppet/parser/resource.rb', line 17

def file
  @file
end

#lineObject

Returns the value of attribute line.



17
18
19
# File 'lib/puppet/parser/resource.rb', line 17

def line
  @line
end

#overrideObject

Returns the value of attribute override.



16
17
18
# File 'lib/puppet/parser/resource.rb', line 16

def override
  @override
end

#parametersObject (readonly)

Returns the value of attribute parameters.



19
20
21
# File 'lib/puppet/parser/resource.rb', line 19

def parameters
  @parameters
end

#scopeObject

Returns the value of attribute scope.



15
16
17
# File 'lib/puppet/parser/resource.rb', line 15

def scope
  @scope
end

#sourceObject

Returns the value of attribute source.



15
16
17
# File 'lib/puppet/parser/resource.rb', line 15

def source
  @source
end

#translatedObject

Returns the value of attribute translated.



16
17
18
# File 'lib/puppet/parser/resource.rb', line 16

def translated
  @translated
end

#virtualObject

Returns the value of attribute virtual.



16
17
18
# File 'lib/puppet/parser/resource.rb', line 16

def virtual
  @virtual
end

Class Method Details

.relationship_parameter?(name) ⇒ Boolean

Determine whether the provided parameter name is a relationship parameter.

Returns:

  • (Boolean)


22
23
24
25
# File 'lib/puppet/parser/resource.rb', line 22

def self.relationship_parameter?(name)
  @relationship_names ||= Puppet::Type.relationship_params.collect { |p| p.name }
  @relationship_names.include?(name)
end

Instance Method Details

#[](param) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/puppet/parser/resource.rb', line 32

def [](param)
  param = param.intern
  if param == :title
    return self.title
  end
  if @parameters.has_key?(param)
    @parameters[param].value
  else
    nil
  end
end

#add_edge_to_stageObject

Process the stage metaparameter for a class. A containment edge is drawn from the class to the stage. The stage for containment defaults to main, if none is specified.



57
58
59
60
61
62
63
64
65
66
# File 'lib/puppet/parser/resource.rb', line 57

def add_edge_to_stage
  return unless self.class?

  unless stage = catalog.resource(:stage, self[:stage] || (scope && scope.resource && scope.resource[:stage]) || :main)
    raise ArgumentError, _("Could not find stage %{stage} specified by %{resource}") % { stage: self[:stage] || :main, resource: self }
  end

  self[:stage] ||= stage.title unless stage.title == :main
  catalog.add_edge(stage, self)
end

#add_parameters_from_consumeObject

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.

Fills resource params from a capability

This backs ‘consumes => Sql



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/puppet/parser/resource.rb', line 260

def add_parameters_from_consume
  return if self[:consume].nil?

  map = {}
  [ self[:consume] ].flatten.map do |ref|
    # Assert that the ref really is a resource reference
    raise Puppet::Error, _("Invalid consume in %{value0}: %{ref} is not a resource") % { value0: self.ref, ref: ref } unless ref.is_a?(Puppet::Resource)

    # Resolve references
    t = ref.type
    t = Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_resource_type(scope, t) unless t == 'class' || t == 'node'
    cap = catalog.resource(t, ref.title)
    if cap.nil?
      raise Puppet::Error, _("Resource %{ref} could not be found; it might not have been produced yet") % { ref: ref }
    end

    # Ensure that the found resource is a capability resource
    raise Puppet::Error, _("Invalid consume in %{ref}: %{cap} is not a capability resource") % { ref: ref, cap: cap } unless cap.resource_type.is_capability?
    cap
  end.each do |cns|
    # Establish mappings
    blueprint = resource_type.consumes.find do |bp|
      bp[:capability] == cns.type
    end
    # @todo lutter 2015-08-03: catch this earlier, can we do this during
    # static analysis ?
    raise _("Resource %{res} tries to consume %{cns} but no 'consumes' mapping exists for %{resource_type} and %{cns_type}") % { res: self, cns: cns, resource_type: self.resource_type, cns_type: cns.type } unless blueprint

    # setup scope that has, for each attr of cns, a binding to cns[attr]
    scope.with_global_scope do |global_scope|
      cns_scope = global_scope.newscope(:source => self, :resource => self)
      cns.to_hash.each { |name, value| cns_scope[name.to_s] = value }

      # evaluate mappings in that scope
      resource_type.arguments.keys.each do |name|
        if expr = blueprint[:mappings][name]
          # Explicit mapping
          value = expr.safeevaluate(cns_scope)
        else
          value = cns[name]
        end
        unless value.nil?
          # @todo lutter 2015-07-01: this should be caught by the checker
          # much earlier. We consume several capres, at least two of which
          # want to map to the same parameter (PUP-5080)
          raise _("Attempt to reassign attribute '%{name}' in '%{resource}' caused by multiple consumed mappings to the same attribute") % { name: name, resource: self } if map[name]
          map[name] = value
        end
      end
    end
  end

  map.each { |name, value| self[name] = value if self[name].nil? }
end

#eachparamObject



44
45
46
47
48
# File 'lib/puppet/parser/resource.rb', line 44

def eachparam
  @parameters.each do |name, param|
    yield param
  end
end

#environmentObject



50
51
52
# File 'lib/puppet/parser/resource.rb', line 50

def environment
  scope.environment
end

#evaluateObject

Retrieve the associated definition and evaluate it.



69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/puppet/parser/resource.rb', line 69

def evaluate
  return if evaluated?
  Puppet::Util::Profiler.profile(_("Evaluated resource %{res}") % { res: self }, [:compiler, :evaluate_resource, self]) do
    @evaluated = true
    if builtin_type?
      devfail "Cannot evaluate a builtin type (#{type})"
    elsif resource_type.nil?
      self.fail "Cannot find definition #{type}"
    else
      finish_evaluation() # do not finish completely (as that destroys Sensitive data)
      resource_type.evaluate_code(self)
    end
  end
end

#evaluated?Boolean

Returns:

  • (Boolean)


30
# File 'lib/puppet/parser/resource.rb', line 30

def evaluated?;  !!@evaluated;  end

#finish(do_validate = true) ⇒ 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.

Do any finishing work on this object, called before storage/translation. The method does nothing the second time it is called on the same resource.

Parameters:

  • do_validate (Boolean) (defaults to: true)

    true if validation should be performed



111
112
113
114
115
116
117
# File 'lib/puppet/parser/resource.rb', line 111

def finish(do_validate = true)
  return if finished?
  @finished = true
  finish_evaluation
  replace_sensitive_data
  validate if do_validate
end

#finish_evaluationObject

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.

Finish the evaluation by assigning defaults and scope tags



98
99
100
101
102
# File 'lib/puppet/parser/resource.rb', line 98

def finish_evaluation
  return if @evaluation_finished
  add_scope_tags
  @evaluation_finished = true
end

#finished?Boolean

Has this resource already been finished?

Returns:

  • (Boolean)


120
121
122
# File 'lib/puppet/parser/resource.rb', line 120

def finished?
  @finished
end

#is_unevaluated_consumer?Boolean

Returns:

  • (Boolean)


153
154
155
156
# File 'lib/puppet/parser/resource.rb', line 153

def is_unevaluated_consumer?
  # We don't declare a new variable here just to test. Saves memory
  instance_variable_defined?(:@unevaluated_consumer)
end

#isomorphic?Boolean

Is this resource modeling an isomorphic resource type?

Returns:

  • (Boolean)


145
146
147
148
149
150
151
# File 'lib/puppet/parser/resource.rb', line 145

def isomorphic?
  if builtin_type?
    return resource_type.isomorphic?
  else
    return true
  end
end

#mark_unevaluated_consumerObject



158
159
160
# File 'lib/puppet/parser/resource.rb', line 158

def mark_unevaluated_consumer
  @unevaluated_consumer = true
end

#merge(resource) ⇒ Object

Merge an override resource in. This will throw exceptions if any overrides aren’t allowed.



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/puppet/parser/resource.rb', line 164

def merge(resource)
  # Test the resource scope, to make sure the resource is even allowed
  # to override.
  unless self.source.object_id == resource.source.object_id || resource.source.child_of?(self.source)
    raise Puppet::ParseError.new(_("Only subclasses can override parameters"), resource.file, resource.line)
  end

  if evaluated?
    strict = Puppet[:strict]
    unless strict == :off
      msg = _('Attempt to override an already evaluated resource%{location} with new values') %
        { resource: ref, location: append_location(file, line, _(', defined'), ',') }
      raise Puppet::ParseError.new(msg, resource.file, resource.line) if strict == :error
      msg << append_location(resource.file, resource.line)
      Puppet.warning(msg)
    end
  end

  # Some of these might fail, but they'll fail in the way we want.
  resource.parameters.each do |name, param|
    override_parameter(param)
  end
end

#nameObject



188
189
190
# File 'lib/puppet/parser/resource.rb', line 188

def name
  self[:name] || self.title
end

#offsetObject



315
316
317
# File 'lib/puppet/parser/resource.rb', line 315

def offset
  nil
end

#override?Boolean

Returns:

  • (Boolean)


29
# File 'lib/puppet/parser/resource.rb', line 29

def override?;   !!@override;   end

#posObject



319
320
321
# File 'lib/puppet/parser/resource.rb', line 319

def pos
  nil
end

#raw_tagged?(tag_array) ⇒ Boolean

Answers if this resource is tagged with at least one of the tags given in downcased string form.

The method is a faster variant of the tagged? method that does no conversion of its arguments.

The match takes into account the tags that a resource will inherit from its container but have not been set yet. It does not take tags set via resource defaults as these will never be set on the resource itself since all resources always have tags that are automatically assigned.

Parameters:

  • tag_array (Array[String])

    list tags to look for

Returns:

  • (Boolean)

    true if this instance is tagged with at least one of the provided tags



252
253
254
# File 'lib/puppet/parser/resource.rb', line 252

def raw_tagged?(tag_array)
  super || ((scope_resource = scope.resource) && !scope_resource.equal?(self) && scope_resource.raw_tagged?(tag_array))
end

#set_parameter(param, value = nil) ⇒ Object Also known as: []=

Define a parameter in our resource. if we ever receive a parameter named ‘tag’, set the resource tags with its value.



198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/puppet/parser/resource.rb', line 198

def set_parameter(param, value = nil)
  if ! param.is_a?(Puppet::Parser::Resource::Param)
    param = param.name if param.is_a?(Puppet::Pops::Resource::Param)
    param = Puppet::Parser::Resource::Param.new(
      :name => param, :value => value, :source => self.source
    )
  end

  tag(*param.value) if param.name == :tag

  # And store it in our parameter hash.
  @parameters[param.name] = param
end

#to_hashObject



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/puppet/parser/resource.rb', line 213

def to_hash
  parse_title.merge(@parameters.reduce({}) do |result, (_, param)|
    value = param.value
    value = (:undef == value) ? nil : value

    unless value.nil?
      case param.name
      when :before, :subscribe, :notify, :require
        if value.is_a?(Array)
          value = value.flatten.reject {|v| v.nil? || :undef == v }
        end
        result[param.name] = value
      else
        result[param.name] = value
      end
    end
    result
  end)
end

#to_ralObject

Convert this resource to a RAL resource.



234
235
236
# File 'lib/puppet/parser/resource.rb', line 234

def to_ral
  copy_as_resource.to_ral
end

#translated?Boolean

Set up some boolean test methods

Returns:

  • (Boolean)


28
# File 'lib/puppet/parser/resource.rb', line 28

def translated?; !!@translated; end