Class: Puppet::Parameter

Inherits:
Object show all
Extended by:
Util, Util::Docs
Includes:
Util, Util::Errors, Util::Logging
Defined in:
lib/puppet/parameter.rb

Overview

The Parameter class is the implementation of a resource’s attributes of parameter kind. The Parameter class is also the base class for Property, and is used to describe meta-parameters (parameters that apply to all resource types). A Parameter (in contrast to a Property) has a single value where a property has both a current and a wanted value. The Parameter class methods are used to configure and create an instance of Parameter that represents one particular attribute data type; its valid value(s), and conversion to/from internal form.

The intention is that a new parameter is created by using the DSL method Type.newparam, or Type.newmetaparam if the parameter should be applicable to all resource types.

A Parameter that does not specify and valid values (via Parameter.newvalues) accepts any value.

See Also:

Defined Under Namespace

Classes: Boolean, PackageOptions, Path, Value, ValueCollection

Constant Summary

Constants included from Util::Docs

Util::Docs::HEADER_LEVELS

Constants included from Util

Util::ALNUM, Util::ALPHA, Util::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE, Util::ESCAPED, Util::HEX, Util::HttpProxy, Util::PUPPET_STACK_INSERTION_FRAME, Util::RESERVED, Util::RFC_3986_URI_REGEX, Util::UNRESERVED, Util::UNSAFE

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

Class Attribute Summary collapse

Instance Attribute Summary collapse

Attributes included from Util::Docs

#doc, #nodoc

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util::Docs

desc, dochook, doctable, markdown_definitionlist, markdown_header, nodoc?, pad, scrub

Methods included from Util

absolute_path?, benchmark, chuser, clear_environment, create_erb, default_env, deterministic_rand, deterministic_rand_int, exit_on_fail, format_backtrace_array, format_puppetstack_frame, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, resolve_stackframe, rfc2396_escape, safe_posix_fork, set_env, skip_external_facts, symbolizehash, thinmark, uri_encode, uri_query_encode, uri_to_path, uri_unescape, which, withenv, withumask

Methods included from Util::POSIX

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

Methods included from Util::SymbolicFileMode

#display_mode, #normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Methods included from Util::Logging

#clear_deprecation_warnings, #debug, #deprecation_warning, #format_backtrace, #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, error_location, error_location_with_space, error_location_with_unknowns, #exceptwrap, #fail

Constructor Details

#initialize(resource: nil, value: nil, should: nil) ⇒ Parameter

Note:

A parameter should be created via the DSL method Type::newparam

Initializes the parameter with a required resource reference and optional attribute settings. The option ‘:resource` must be specified or an exception is raised. Any additional options passed are used to initialize the attributes of this parameter by treating each key in the `options` hash as the name of the attribute to set, and the value as the value to set.

Parameters:

  • options (Hash{Symbol => Object])

    Options, where ‘resource` is required

Raises:



346
347
348
349
350
351
352
353
354
355
# File 'lib/puppet/parameter.rb', line 346

def initialize(resource: nil, value: nil, should: nil)
  if resource
    self.resource = resource
  else
    raise Puppet::DevError, _("No resource set for %{name}") % { name: self.class.name }
  end

  self.value = value if value
  self.should = should if should
end

Class Attribute Details

.defaultObject (readonly)

Returns The default value of the parameter as determined by the defaultto method, or nil if no default has been set.

Returns:

  • (Object)

    The default value of the parameter as determined by the defaultto method, or nil if no default has been set.



38
39
40
# File 'lib/puppet/parameter.rb', line 38

def default
  @default
end

.metaparamBoolean

Returns Flag indicating whether this parameter is a meta-parameter or not.

Returns:

  • (Boolean)

    Flag indicating whether this parameter is a meta-parameter or not.



67
68
69
# File 'lib/puppet/parameter.rb', line 67

def metaparam
  @metaparam
end

.nameSymbol (readonly)

Returns The parameter name as given when it was created.

Returns:

  • (Symbol)

    The parameter name as given when it was created.



34
35
36
# File 'lib/puppet/parameter.rb', line 34

def name
  @name
end

.required_featuresArray<Symbol> .required_features=(*args) ⇒ Array<Symbol>

Returns The names of the _provider features_ required for this parameter to work. the returned names are always all lower case symbols.

Overloads:

  • .required_featuresArray<Symbol>

    Returns the required _provider features_ as an array of lower case symbols

  • .required_features=(*args) ⇒ Array<Symbol>

    Sets the required_provider_features_ from one or more values, or array. The given arguments are flattened, and internalized.

    Parameters:

    • *args (Symbol)

      one or more names of required provider features

Returns:

  • (Array<Symbol>)

    The names of the _provider features_ required for this parameter to work. the returned names are always all lower case symbols.



59
60
61
# File 'lib/puppet/parameter.rb', line 59

def required_features
  @required_features
end

.value_collectionPuppet::Parameter::ValueCollection (readonly)

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.

Returns The set of valid values (or an empty set that accepts any value).

Returns:



64
65
66
# File 'lib/puppet/parameter.rb', line 64

def value_collection
  @value_collection
end

Instance Attribute Details

#nameSymbol (readonly)

Note:

Since a Parameter defines the name at the class level, each Parameter class must be unique within a type’s inheritance chain.

Returns The parameter’s name as given when it was created.

Returns:

  • (Symbol)

    The parameter’s name as given when it was created.



379
380
381
# File 'lib/puppet/parameter.rb', line 379

def name
  self.class.name
end

#parentPuppet::Parameter

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.

Returns A reference to the parameter’s parent kept for backwards compatibility.

Returns:

  • (Puppet::Parameter)

    A reference to the parameter’s parent kept for backwards compatibility.



308
309
310
# File 'lib/puppet/parameter.rb', line 308

def parent
  @parent
end

#resourcePuppet::Resource

Returns A reference to the resource this parameter is an attribute of (the _associated resource_).

Returns:

  • (Puppet::Resource)

    A reference to the resource this parameter is an attribute of (the _associated resource_).



302
303
304
# File 'lib/puppet/parameter.rb', line 302

def resource
  @resource
end

#sensitivetrue, false

Returns If this parameter has been tagged as sensitive.

Returns:

  • (true, false)

    If this parameter has been tagged as sensitive.



312
313
314
# File 'lib/puppet/parameter.rb', line 312

def sensitive
  @sensitive
end

Class Method Details

.aliasvalue(name, other) ⇒ Object

Makes the given ‘name` an alias for the given `other` name. Or said differently, the valid value `other` can now also be referred to via the given `name`. Aliasing may affect how the parameter’s value is serialized/stored (it may store the ‘other` value instead of the alias).



278
279
280
# File 'lib/puppet/parameter.rb', line 278

def aliasvalue(name, other)
  @value_collection.aliasvalue(name, other)
end

.defaultto(value) ⇒ void .defaultto({ ... }) ⇒ void

This method returns an undefined value.

Defines how the ‘default` value of a parameter is computed. The computation of the parameter’s default value is defined by providing a value or a block. A default of ‘nil` can not be used.

Overloads:

  • .defaultto(value) ⇒ void

    Defines the default value with a literal value

    Parameters:

    • value (Object)

      the literal value to use as the default value

  • .defaultto({ ... }) ⇒ void

    Defines that the default value is produced by the given block. The given block should produce the default value.

Raises:

See Also:



84
85
86
87
88
89
90
91
92
93
94
# File 'lib/puppet/parameter.rb', line 84

def defaultto(value = nil, &block)
  if block
    define_method(:default, &block)
  else
    if value.nil?
      raise Puppet::DevError,
            "Either a default value or block must be provided"
    end
    define_method(:default) do value end
  end
end

.desc(str) ⇒ String

Sets the documentation for this parameter.

Parameters:

  • str (String)

    The documentation string to set

Returns:

  • (String)

    the given ‘str` parameter

See Also:



154
155
156
# File 'lib/puppet/parameter.rb', line 154

def desc(str)
  @doc = str
end

.docString

Produces a documentation string. If an enumeration of _valid values_ has been defined, it is appended to the documentation for this parameter specified with the desc method.

Returns:

  • (String)

    Returns a documentation string.



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/puppet/parameter.rb', line 112

def doc
  @doc ||= ""

  unless defined?(@addeddocvals)
    @doc = Puppet::Util::Docs.scrub(@doc)
    vals = value_collection.doc
    if vals
      @doc << "\n\n#{vals}"
    end

    features = required_features
    if features
      @doc << "\n\nRequires features #{features.flatten.collect(&:to_s).join(' ')}."
    end
    @addeddocvals = true
  end

  @doc
end

.format_value_for_display(value) ⇒ String

Produces a String with the value formatted for display to a human.

The output is created using the StringConverter with format ‘%#p’ to produce human readable code that is understood by puppet.

Returns:

  • (String)

    The formatted value in string form.



575
576
577
# File 'lib/puppet/parameter.rb', line 575

def self.format_value_for_display(value)
  Puppet::Pops::Types::StringConverter.convert(value, Puppet::Pops::Types::StringConverter::DEFAULT_PARAMETER_FORMAT)
end

.initvarsvoid

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.

This method returns an undefined value.

Initializes the instance variables. Clears the internal value collection (set of allowed values).



163
164
165
# File 'lib/puppet/parameter.rb', line 163

def initvars
  @value_collection = ValueCollection.new
end

.isnamevarvoid

This method returns an undefined value.

Sets a marker indicating that this parameter is the namevar (unique identifier) of the type where the parameter is contained. This also makes the parameter a required value. The marker can not be unset once it has been set.



202
203
204
205
# File 'lib/puppet/parameter.rb', line 202

def isnamevar
  @isnamevar = true
  @required = true
end

.isnamevar?Boolean

Returns whether this parameter is the namevar or not.

Returns:

  • (Boolean)

    Returns whether this parameter is the namevar or not.



210
211
212
# File 'lib/puppet/parameter.rb', line 210

def isnamevar?
  @isnamevar
end

.isrequiredvoid

This method returns an undefined value.

Sets a marker indicating that this parameter is required. Once set, it is not possible to make a parameter optional.



220
221
222
# File 'lib/puppet/parameter.rb', line 220

def isrequired
  @required = true
end

.munge({ ... }) ⇒ Object

Note:

This adds a method with the name ‘unsafe_munge` in the created parameter class. Later this method is called in a context where exceptions will be rescued and handled.

Defines an optional method used to convert the parameter value from DSL/string form to an internal form. If a munge method is not defined, the DSL/string value is used as is.



175
176
177
178
179
180
181
# File 'lib/puppet/parameter.rb', line 175

def munge(&block)
  # I need to wrap the unsafe version in begin/rescue parameterments,
  # but if I directly call the block then it gets bound to the
  # class's context, not the instance's, thus the two methods,
  # instead of just one.
  define_method(:unsafe_munge, &block)
end

.newvalues(*names) ⇒ void

Note:

Each call to this method adds to the set of valid values

This method returns an undefined value.

Defines valid values for the parameter (enumeration or regular expressions). The set of valid values for the parameter can be limited to a (mix of) literal values and regular expression patterns.

Parameters:

  • names (Symbol, Regexp)

    The set of valid literal values and/or patterns for the parameter.



267
268
269
# File 'lib/puppet/parameter.rb', line 267

def newvalues(*names)
  @value_collection.newvalues(*names)
end

.nodefaultvoid

This method returns an undefined value.

Removes the ‘default` method if defined. Has no effect if the default method is not defined. This method is intended to be used in a DSL scenario where a parameter inherits from a parameter with a default value that is not wanted in the derived parameter (otherwise, simply do not define a default value method).

See Also:



143
144
145
# File 'lib/puppet/parameter.rb', line 143

def nodefault
  undef_method :default if public_method_defined? :default
end

.proxymethods(*values) ⇒ 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.

Creates instance (proxy) methods that delegates to a class method with the same name.



286
287
288
289
290
291
292
# File 'lib/puppet/parameter.rb', line 286

def self.proxymethods(*values)
  values.each { |val|
    define_method(val) do
      self.class.send(val)
    end
  }
end

.required?Boolean

Returns whether this parameter is required or not. A parameter is required if a call has been made to the DSL method isrequired.

Returns:

  • (Boolean)

    Returns whether this parameter is required or not.



239
240
241
# File 'lib/puppet/parameter.rb', line 239

def required?
  @required
end

.sensitive(value = nil, &block) ⇒ Object

rubocop:disable Naming/PredicateName



97
98
99
100
101
102
103
# File 'lib/puppet/parameter.rb', line 97

def sensitive(value = nil, &block)
  if block
    define_method(:is_sensitive, &block)
  else
    define_method(:is_sensitive) do value end
  end
end

.unmunge({ ... }) ⇒ Object

Note:

This adds a method with the name ‘unsafe_unmunge` in the created parameter class.

Defines an optional method used to convert the parameter value from internal form to DSL/string form. If an ‘unmunge` method is not defined, the internal form is used.

See Also:



191
192
193
# File 'lib/puppet/parameter.rb', line 191

def unmunge(&block)
  define_method(:unsafe_unmunge, &block)
end

.validate({ ... }) ⇒ void

This method returns an undefined value.

Defines an optional method that is used to validate the parameter’s DSL/string value. Validation should raise appropriate exceptions, the return value of the given block is ignored. The easiest way to raise an appropriate exception is to call the method Util::Errors.fail with the message as an argument. To validate the munged value instead, just munge the value (‘munge(value)`).



254
255
256
# File 'lib/puppet/parameter.rb', line 254

def validate(&block)
  define_method(:unsafe_validate, &block)
end

Instance Method Details

#fileInteger

Returns the result of calling the same method on the associated resource.

Returns:

  • (Integer)

    Returns the result of calling the same method on the associated resource.



327
328
329
# File 'lib/puppet/parameter.rb', line 327

def file
  resource.file
end

#format(fmt, *args) ⇒ String

Note:

Because the default implementation of Puppet::Property#is_to_s returns the current value as-is, it doesn’t necessarily return a string. For the sake of sanity we just cast everything to a string for interpolation so we don’t introduce issues with unexpected property values.

Formats the given string and conditionally redacts the provided interpolation variables, depending on if this property is sensitive.

Parameters:

  • fmt (String)

    The format string to interpolate.

  • args (Array<String>)

    One or more strings to conditionally redact and interpolate into the format string.

Returns:

  • (String)

See Also:

  • String#format


564
565
566
# File 'lib/puppet/parameter.rb', line 564

def format(fmt, *args)
  fmt % args.map { |arg| @sensitive ? "[redacted]" : arg.to_s }
end

#isnamevar?Object



299
# File 'lib/puppet/parameter.rb', line 299

proxymethods("required?", "isnamevar?")

#lineInteger

Returns the result of calling the same method on the associated resource.

Returns:

  • (Integer)

    Returns the result of calling the same method on the associated resource.



322
323
324
# File 'lib/puppet/parameter.rb', line 322

def line
  resource.line
end

#log(msg) ⇒ void

TODO:

is loglevel a metaparameter? it is looked up with ‘resource`

This method returns an undefined value.

Writes the given ‘msg` to the log with the loglevel indicated by the associated resource’s ‘loglevel` parameter.



362
363
364
# File 'lib/puppet/parameter.rb', line 362

def log(msg)
  send_log(resource[:loglevel], msg)
end

#metaparam?Boolean

Returns whether this parameter is a meta-parameter or not.

Returns:

  • (Boolean)

    Returns whether this parameter is a meta-parameter or not.



367
368
369
# File 'lib/puppet/parameter.rb', line 367

def metaparam?
  self.class.metaparam
end

#munge(value) ⇒ Object

Note:

This method should not be overridden. Use the DSL method munge to define a munging method if required.

Munges the value from DSL form to internal form. This implementation of ‘munge` provides exception handling around the specified munging of this parameter.

Parameters:

  • value (Object)

    the DSL value to munge

Returns:

  • (Object)

    the munged (internal) value



440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'lib/puppet/parameter.rb', line 440

def munge(value)
  return value if value.is_a?(Puppet::Pops::Evaluator::DeferredValue)

  begin
    ret = unsafe_munge(value)
  rescue Puppet::Error => detail
    Puppet.debug { "Reraising #{detail}" }
    raise
  rescue => detail
    raise Puppet::DevError, _("Munging failed for value %{value} in class %{class_name}: %{detail}") % { value: value.inspect, class_name: name, detail: detail }, detail.backtrace
  end
  ret
end

#noopBoolean

TODO:

How is noop mode set for a parameter? Is this of value in DSL to inhibit a parameter?

Returns true if this parameter, the associated resource, or overall puppet mode is ‘noop`.

Returns:

  • (Boolean)

    Returns true if this parameter, the associated resource, or overall puppet mode is ‘noop`.



386
387
388
389
# File 'lib/puppet/parameter.rb', line 386

def noop
  @noop ||= false
  @noop || resource.noop || Puppet[:noop] || false
end

#pathString

Returns a string representation of the resource’s containment path in the catalog.

Returns:

  • (String)


317
318
319
# File 'lib/puppet/parameter.rb', line 317

def path
  @path ||= '/' + pathbuilder.join('/')
end

#pathbuilderObject

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.

Returns an array of strings representing the containment hierarchy (types/classes) that make up the path to the resource from the root of the catalog. This is mostly used for logging purposes.



396
397
398
399
400
401
402
# File 'lib/puppet/parameter.rb', line 396

def pathbuilder
  if @resource
    [@resource.pathbuilder, name]
  else
    [name]
  end
end

#providerPuppet::Provider

TODO:

The original comment says = _“Retrieve the resource’s provider. Some types don’t have providers, in which case we return the resource object itself.”_ This does not seem to be true, the default implementation that sets this value may be Type.provider= which always gets either the name of a provider or an instance of one.

Returns the provider of the associated resource.

Returns:



525
526
527
# File 'lib/puppet/parameter.rb', line 525

def provider
  @resource.provider
end

#removenil

TODO:

Why - what is the intent/purpose of this?

Sets the associated resource to nil.

Returns:

  • (nil)


493
494
495
# File 'lib/puppet/parameter.rb', line 493

def remove
  @resource = nil
end

#required?Object



299
# File 'lib/puppet/parameter.rb', line 299

proxymethods("required?", "isnamevar?")

#tagsArray<Symbol>

TODO:

The original comment says = _“The properties need to return tags so that logs correctly collect them.”_ what if anything of that is of interest to document. Should tags and their relationship to logs be described. This is a more general concept.

Returns an array of the associated resource’s symbolic tags (including the parameter itself). At a minimum, the array contains the name of the parameter. If the associated resource has tags, these tags are also included in the array.

Returns:

  • (Array<Symbol>)

    Returns an array of the associated resource’s symbolic tags (including the parameter itself).



537
538
539
540
541
542
543
544
545
# File 'lib/puppet/parameter.rb', line 537

def tags
  unless defined?(@tags)
    @tags = []
    # This might not be true in testing
    @tags = @resource.tags if @resource.respond_to? :tags
    @tags << name.to_s
  end
  @tags
end

#to_sString

Returns The name of the parameter in string form.

Returns:

  • (String)

    The name of the parameter in string form.



548
549
550
# File 'lib/puppet/parameter.rb', line 548

def to_s
  name.to_s
end

#unmunge(value) ⇒ Object

Unmunges the value by transforming it from internal form to DSL form. This is the default implementation of ‘unmunge` that simply returns the value without processing. The DSL method unmunge should be used to define an overriding method if required.

Returns:

  • (Object)

    the unmunged value



418
419
420
421
422
# File 'lib/puppet/parameter.rb', line 418

def unmunge(value)
  return value if value.is_a?(Puppet::Pops::Evaluator::DeferredValue)

  unsafe_unmunge(value)
end

#unsafe_munge(value) ⇒ 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.

This is the default implementation of ‘munge` that simply produces the value (if it is valid). The DSL method munge should be used to define an overriding method if munging is required.



409
410
411
# File 'lib/puppet/parameter.rb', line 409

def unsafe_munge(value)
  self.class.value_collection.munge(value)
end

#unsafe_unmunge(value) ⇒ 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.

This is the default implementation of ‘unmunge` that simply produces the value (if it is valid). The DSL method unmunge should be used to define an overriding method if unmunging is required.



429
430
431
# File 'lib/puppet/parameter.rb', line 429

def unsafe_unmunge(value)
  value
end

#unsafe_validate(value) ⇒ void

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.

This method returns an undefined value.

This is the default implementation of ‘validate` that may be overridden by the DSL method validate. If no valid values have been defined, the given value is accepted, else it is validated against the literal values (enumerator) and/or patterns defined by calling newvalues.

Parameters:

  • value (Object)

    the value to check for validity

Raises:

  • (ArgumentError)

    if the value is not valid



463
464
465
# File 'lib/puppet/parameter.rb', line 463

def unsafe_validate(value)
  self.class.value_collection.validate(value)
end

#validate(value) ⇒ void

TODO:

Better description of when the various exceptions are raised.ArgumentError is rescued and changed into Puppet::Error.

This method returns an undefined value.

Performs validation of the given value against the rules defined by this parameter. A protected validation method that only ever raises useful exceptions.

Raises:



475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/puppet/parameter.rb', line 475

def validate(value)
  return if value.is_a?(Puppet::Pops::Evaluator::DeferredValue)

  begin
    unsafe_validate(value)
  rescue ArgumentError => detail
    self.fail Puppet::Error, detail.to_s, detail
  rescue Puppet::Error, TypeError
    raise
  rescue => detail
    raise Puppet::DevError, _("Validate method failed for class %{class_name}: %{detail}") % { class_name: name, detail: detail }, detail.backtrace
  end
end

#valueObject

Returns Gets the value of this parameter after performing any specified unmunging.

Returns:

  • (Object)

    Gets the value of this parameter after performing any specified unmunging.



498
499
500
# File 'lib/puppet/parameter.rb', line 498

def value
  unmunge(@value) unless @value.nil?
end

#value=(value) ⇒ Object

TODO:

This original comment _“All of the checking should possibly be late-binding (e.g., users might not exist when the value is assigned but might when it is asked for).”_ does not seem to be correct, the implementation calls both validate and munge on the given value, so no late binding.

Sets the given value as the value of this parameter. The given value is validated and then munged (if munging has been specified). The result is store as the value of this parameter.

Returns:

  • (Object)

    The given ‘value` after munging.

Raises:



513
514
515
516
517
# File 'lib/puppet/parameter.rb', line 513

def value=(value)
  validate(value)

  @value = munge(value)
end

#versionInteger

Returns the result of calling the same method on the associated resource.

Returns:

  • (Integer)

    Returns the result of calling the same method on the associated resource.



332
333
334
# File 'lib/puppet/parameter.rb', line 332

def version
  resource.version
end