Class: Puppet::Type

Overview

Note:

The Type class deals with multiple concerns; some methods provide an internal DSL for convenient definition of types, other methods deal with various aspects while running; wiring up a resource (expressed in Puppet DSL) with its _resource type_ (i.e. an instance of Type) to enable validation, transformation of values (munge/unmunge), etc. Lastly, Type is also responsible for dealing with Providers; the concrete implementations of the behavior that constitutes how a particular Type behaves on a particular type of system (e.g. how commands are executed on a flavor of Linux, on Windows, etc.). This means that as you are reading through the documentation of this class, you will be switching between these concepts, as well as switching between the conceptual level “a resource is an instance of a resource-type” and the actual implementation classes (Type, Resource, Provider, and various utility and helper classes).

The base class for all Puppet types.

A type describes: –

  • *Attributes* - properties, parameters, and meta-parameters are different types of attributes of a type.

    • *Properties* - these are the properties of the managed resource (attributes of the entity being managed; like a file's owner, group and mode). A property describes two states; the 'is' (current state) and the 'should' (wanted state).

      * **Ensurable** - a set of traits that control the lifecycle (create, remove, etc.) of a managed entity.
        There is a default set of operations associated with being _ensurable_, but this can be changed.
      * **Name/Identity** - one property is the name/identity of a resource, the _namevar_ that uniquely identifies
        one instance of a type from all others.
      
    • *Parameters* - additional attributes of the type (that does not directly related to an instance of the managed resource; if an operation is recursive or not, where to look for things, etc.). A Parameter (in contrast to Property) has one current value where a Property has two (current-state and wanted-state).

    • *Meta-Parameters* - parameters that are available across all types. A meta-parameter typically has additional semantics; like the `require` meta-parameter. A new type typically does not add new meta-parameters, but you need to be aware of their existence so you do not inadvertently shadow an existing meta-parameters.

  • *Parent* - a type can have a super type (that it inherits from).

  • *Validation* - If not just a basic data type, or an enumeration of symbolic values, it is possible to provide

    validation logic for a type, properties and parameters.
    
  • *Munging* - munging/unmunging is the process of turning a value in external representation (as used

    by a provider) into an internal representation and vice versa. A Type supports adding custom logic for these.
    
  • **Auto Requirements** - a type can specify automatic relationships to resources to ensure that if they are being

    managed, they will be processed before this type.
    
  • *Providers* - a provider is an implementation of a type's behavior - the management of a resource in the

    system being managed. A provider is often platform specific and is selected at runtime based on
    criteria/predicates specified in the configured providers. See {Puppet::Provider} for details.
    
  • **Device Support** - A type has some support for being applied to a device; i.e. something that is managed

    by running logic external to the device itself. There are several methods that deals with type
    applicability for these special cases such as {apply_to_device}.
    

Additional Concepts: –

  • *Resource-type* - A _resource type_ is a term used to denote the type of a resource; internally a resource

    is really an instance of a Ruby class i.e. {Puppet::Resource} which defines its behavior as "resource data".
    Conceptually however, a resource is an instance of a subclass of Type (e.g. File), where such a class describes
    its interface (what can be said/what is known about a resource of this type),
    
  • **Managed Entity** - This is not a term in general use, but is used here when there is a need to make

    a distinction between a resource (a description of what/how something should be managed), and what it is
    managing (a file in the file system). The term _managed entity_ is a reference to the "file in the file system"
    
  • *Isomorphism* - the quality of being isomorphic means that two resource instances with the same name

    refers to the same managed entity. Or put differently; _an isomorphic name is the identity of a resource_.
    As an example, `exec` resources (that executes some command) have the command (i.e. the command line string) as
    their name, and these resources are said to be non-isomorphic.
    

Defined Under Namespace

Classes: RelationshipMetaparam

Constant Summary

Constants included from Util

Util::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE, Util::PUPPET_STACK_INSERTION_FRAME, Util::RFC_3986_URI_REGEX

Constants included from Util::SymbolicFileMode

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

Constants included from Util::POSIX

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

Constants included from Util::Docs

Util::Docs::HEADER_LEVELS

Constants included from Util::Tagging

Util::Tagging::ValidTagRegex

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::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

absolute_path?, benchmark, chuser, clear_environment, 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, 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::SymbolicFileMode

#normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Methods included from Util::POSIX

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

Methods included from Enumerable

uniq

Methods included from Util::ProviderFeatures

feature, feature_module, featuredocs, features, provider_feature

Methods included from Util::Docs

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

Methods included from Util::Warnings

clear_warnings, debug_once, maybe_log, notice_once, warnonce

Methods included from Util::ClassGen

genclass, genmodule, rmclass

Methods included from MetaType::Manager

allclear, clear_misses, eachtype, loadall, newtype, rmtype, typeloader

Methods included from CompilableResourceType

is_3x_ruby_plugin?

Methods included from Util::Tagging

#merge_into, #merge_tags_from, #raw_tagged?, #set_tags, #tag, #tag_if_valid, #tagged?, #tags, #valid_tag?

Methods included from Util::Errors

#adderrorcontext, #devfail, #error_context, error_location, error_location_with_space, error_location_with_unknowns, #exceptwrap, #fail

Constructor Details

#initialize(hash) ⇒ Type #initialize(resource) ⇒ Type

TODO:

Unclear if this is a new Type or a new instance of a given type (the initialization ends with calling validate - which seems like validation of an instance of a given type, not a new meta type.

TODO:

Explain what the Hash and Resource are. There seems to be two different types of resources; one that causes the title to be set to resource.title, and one that causes the title to be resource.ref (“for components”) - what is a component?

Creates an instance of Type from a hash or a Resource.

Overloads:

  • #initialize(hash) ⇒ Type

    Parameters:

    • hash (Hash)

    Raises:

  • #initialize(resource) ⇒ Type

    Parameters:

    • resource (Puppet:Resource)

    Raises:


2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
# File 'lib/puppet/type.rb', line 2421

def initialize(resource)
  resource = self.class.hash2resource(resource) unless resource.is_a?(Puppet::Resource)

  # The list of parameter/property instances.
  @parameters = {}

  # Set the title first, so any failures print correctly.
  if resource.type.to_s.downcase.to_sym == self.class.name
    self.title = resource.title
  else
    # This should only ever happen for components
    self.title = resource.ref
  end

  [:file, :line, :catalog, :exported, :virtual].each do |getter|
    setter = getter.to_s + "="
    val = resource.send(getter)
    self.send(setter, val) if val
  end

  merge_tags_from(resource)

  @original_parameters = resource.to_hash

  set_name(@original_parameters)

  set_default(:provider)

  set_parameters(@original_parameters)

  begin
    self.validate if self.respond_to?(:validate)
  rescue Puppet::Error, ArgumentError => detail
    error = Puppet::ResourceError.new("Validation of #{ref} failed: #{detail}")
    adderrorcontext(error, detail)
    raise error
  end

  set_sensitive_parameters(resource.sensitive_parameters)
end

Class Attribute Details

.defaultproviderPuppet::Provider?

Note:

a warning will be issued if no default provider has been configured and a search for the most suitable provider returns more than one equally suitable provider.

The default provider, or the most suitable provider if no default provider was set.

Returns:

  • (Puppet::Provider, nil)

    the default or most suitable provider, or nil if no provider was found


1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
# File 'lib/puppet/type.rb', line 1811

def self.defaultprovider
  return @defaultprovider if @defaultprovider

  suitable = suitableprovider

  # Find which providers are a default for this system.
  defaults = suitable.find_all { |provider| provider.default? }

  # If we don't have any default we use suitable providers
  defaults = suitable if defaults.empty?
  max = defaults.collect { |provider| provider.specificity }.max
  defaults = defaults.find_all { |provider| provider.specificity == max }

  if defaults.length > 1
    Puppet.warning(_("Found multiple default providers for %{name}: %{provider_list}; using %{selected_provider}") %
                       { name: self.name, provider_list:  defaults.collect { |i| i.name.to_s }.join(", "), selected_provider: defaults[0].name })
  end

  @defaultprovider = defaults.shift unless defaults.empty?
end

.is_capabilityObject

Deprecated.

application orchestration will be removed in puppet 7


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

def is_capability
  @is_capability
end

.nameString (readonly)

Returns the name of the resource type; e.g., “File”.

Returns:

  • (String)

    the name of the resource type; e.g., “File”


2295
2296
2297
# File 'lib/puppet/type.rb', line 2295

def name
  @name
end

.propertiesArray<Puppet::Property> (readonly)

The returned lists contains instances if Puppet::Property or its subclasses.

Returns:

  • (Array<Puppet::Property>)

    The list of declared properties for the resource type.


114
115
116
# File 'lib/puppet/type.rb', line 114

def properties
  @properties
end

.providerloaderObject

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.

The loader of providers to use when loading providers from disk. Although it looks like this attribute provides a way to operate with different loaders of providers that is not the case; the attribute is written when a new type is created, and should not be changed thereafter.


1797
1798
1799
# File 'lib/puppet/type.rb', line 1797

def providerloader
  @providerloader
end

.self_refreshBoolean

Returns true if the type should send itself a refresh event on change.

Returns:

  • (Boolean)

    true if the type should send itself a refresh event on change.


2299
2300
2301
# File 'lib/puppet/type.rb', line 2299

def self_refresh
  @self_refresh
end

Instance Attribute Details

#catalog??? TODO

TODO:

what does this mean “this resource” (sounds like this if for an instance of the type, not the meta Type), but not sure if this is about the catalog where the meta Type is included)

Returns The catalog that this resource is stored in.

Returns:

  • (??? TODO)

    The catalog that this resource is stored in.


2373
2374
2375
# File 'lib/puppet/type.rb', line 2373

def catalog
  @catalog
end

#exportedBoolean

Returns Flag indicating if this type is exported.

Returns:

  • (Boolean)

    Flag indicating if this type is exported


2376
2377
2378
# File 'lib/puppet/type.rb', line 2376

def exported
  @exported
end

#fileString

Returns The file from which this type originates from.

Returns:

  • (String)

    The file from which this type originates from


2365
2366
2367
# File 'lib/puppet/type.rb', line 2365

def file
  @file
end

#lineInteger

Returns The line in #file from which this type originates from.

Returns:

  • (Integer)

    The line in #file from which this type originates from


2368
2369
2370
# File 'lib/puppet/type.rb', line 2368

def line
  @line
end

#noopBoolean

Returns the `noop` run mode status of this.

Returns:

  • (Boolean)

    true if running in noop mode.


1195
1196
1197
# File 'lib/puppet/type.rb', line 1195

def noop
  noop?
end

#original_parametersHash (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 hash of parameters originally defined.

Returns:

  • (Hash)

    hash of parameters originally defined


2401
2402
2403
# File 'lib/puppet/type.rb', line 2401

def original_parameters
  @original_parameters
end

#providerPuppet::Provider?

The provider that has been selected for the instance of the resource type.

Returns:

  • (Puppet::Provider, nil)

    the selected provider or nil, if none has been selected


1787
1788
1789
# File 'lib/puppet/type.rb', line 1787

def provider
  @provider
end

#titleString

TODO:

it is somewhat confusing that if the name_var is a valid parameter, it is assumed to be the name_var called :name, but if it is a property, it uses the name_var. It is further confusing as Type in some respects supports multiple namevars.

Returns the title of this object, or its name if title was not explicitly set. If the title is not already set, it will be computed by looking up the #name_var and using that value as the title.

Returns:

  • (String)

    Returns the title of this object, or its name if title was not explicitly set.

Raises:

  • (??? devfail)

    if title is not set, and name_var can not be found.


2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
# File 'lib/puppet/type.rb', line 2665

def title
  unless @title
    if self.class.validparameter?(name_var)
      @title = self[:name]
    elsif self.class.validproperty?(name_var)
      @title = self.should(name_var)
    else
      self.devfail "Could not find namevar #{name_var} for #{self.class.name}"
    end
  end

  @title
end

#virtualBoolean

Returns Flag indicating if the type is virtual (it should not be).

Returns:

  • (Boolean)

    Flag indicating if the type is virtual (it should not be).


2379
2380
2381
# File 'lib/puppet/type.rb', line 2379

def virtual
  @virtual
end

Class Method Details

.allattrsArray<String>

Returns all the attribute names of the type in the appropriate order. The key_attributes come first, then the provider, then the properties, and finally the parameters and metaparams, all in the order they were specified in the respective files.

Returns:

  • (Array<String>)

    all type attribute names in a defined order.


146
147
148
# File 'lib/puppet/type.rb', line 146

def self.allattrs
  key_attributes | (parameters & [:provider]) | properties.collect { |property| property.name } | parameters | metaparams
end

.application?Boolean

Deprecated.

application orchestration will be removed in puppet 7

Returns whether this type represents an application instance; since only defined types, i.e., instances of Puppet::Resource::Type can represent application instances, this implementation always returns false. Having this method though makes code checking whether a resource is an application instance simpler

Returns:

  • (Boolean)

136
137
138
# File 'lib/puppet/type.rb', line 136

def self.application?
    false
end

.apply_toSymbol

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.

Makes this type apply to `:host` if not already applied to something else.

Returns:

  • (Symbol)

    a `:device`, `:host`, or `:both` enumeration


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

def self.apply_to
  @apply_to ||= :host
end

.apply_to_allSymbol

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.

Makes this type applicable to `:both` (i.e. `:host` and `:device`).

Returns:

  • (Symbol)

    Returns `:both`


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

def self.apply_to_all
  @apply_to = :both
end

.apply_to_deviceSymbol

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.

Makes this type applicable to `:device`.

Returns:

  • (Symbol)

    Returns `:device`


251
252
253
# File 'lib/puppet/type.rb', line 251

def self.apply_to_device
  @apply_to = :device
end

.apply_to_hostSymbol

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.

Makes this type applicable to `:host`.

Returns:

  • (Symbol)

    Returns `:host`


259
260
261
# File 'lib/puppet/type.rb', line 259

def self.apply_to_host
  @apply_to = :host
end

.attrclass(name) ⇒ Class?

Returns the class associated with the given attribute name.

Parameters:

  • name (String)

    the name of the attribute to obtain the class for

Returns:

  • (Class, nil)

    the class for the given attribute, or nil if the name does not refer to an existing attribute


154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/puppet/type.rb', line 154

def self.attrclass(name)
  @attrclasses ||= {}

  # We cache the value, since this method gets called such a huge number
  # of times (as in, hundreds of thousands in a given run).
  unless @attrclasses.include?(name)
    @attrclasses[name] = case self.attrtype(name)
    when :property; @validproperties[name]
    when :meta; @@metaparamhash[name]
    when :param; @paramhash[name]
    end
  end
  @attrclasses[name]
end

.attrtype(attr) ⇒ Symbol

Returns the attribute type (`:property`, `;param`, `:meta`).

Returns:

  • (Symbol)

    a symbol describing the type of attribute (`:property`, `;param`, `:meta`)


174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/puppet/type.rb', line 174

def self.attrtype(attr)
  @attrtypes ||= {}
  unless @attrtypes.include?(attr)
    @attrtypes[attr] = case
      when @validproperties.include?(attr); :property
      when @paramhash.include?(attr); :param
      when @@metaparamhash.include?(attr); :meta
      end
  end

  @attrtypes[attr]
end

.autobefore(name, &block) ⇒ Object


2116
2117
2118
2119
# File 'lib/puppet/type.rb', line 2116

def self.autobefore(name, &block)
  @autobefores ||= {}
  @autobefores[name] = block
end

.autonotify(name, &block) ⇒ Object


2126
2127
2128
2129
# File 'lib/puppet/type.rb', line 2126

def self.autonotify(name, &block)
  @autonotifies ||= {}
  @autonotifies[name] = block
end

.autorequire(name) {| | ... } ⇒ void

This method returns an undefined value.

Adds a block producing a single name (or list of names) of the given resource type name to autorelate.

The four relationship types require, before, notify, and subscribe are all supported.

Be careful with notify and subscribe as they may have unintended consequences.

Resources in the catalog that have the named type and a title that is included in the result will be linked to the calling resource as a requirement.

Examples:

Autorequire the files File['foo', 'bar']

autorequire( 'file', {|| ['foo', 'bar'] })

Autobefore the files File['foo', 'bar']

autobefore( 'file', {|| ['foo', 'bar'] })

Autosubscribe the files File['foo', 'bar']

autosubscribe( 'file', {|| ['foo', 'bar'] })

Autonotify the files File['foo', 'bar']

autonotify( 'file', {|| ['foo', 'bar'] })

Parameters:

  • name (String)

    the name of a type of which one or several resources should be autorelated e.g. “file”

Yields:

  • ( )

    a block returning list of names of given type to auto require

Yield Returns:

  • (String, Array<String>)

    one or several resource names for the named type


2111
2112
2113
2114
# File 'lib/puppet/type.rb', line 2111

def self.autorequire(name, &block)
  @autorequires ||= {}
  @autorequires[name] = block
end

.autosubscribe(name, &block) ⇒ Object


2121
2122
2123
2124
# File 'lib/puppet/type.rb', line 2121

def self.autosubscribe(name, &block)
  @autosubscribes ||= {}
  @autosubscribes[name] = block
end

.can_apply_to(target) ⇒ Boolean

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 true if this type is applicable to the given target.

Parameters:

  • target (Symbol)

    should be :device, :host or :target, if anything else, :host is enforced

Returns:

  • (Boolean)

    true


283
284
285
# File 'lib/puppet/type.rb', line 283

def self.can_apply_to(target)
  [ target == :device ? :device : :host, :both ].include?(apply_to)
end

.eachautobefore {|type, block| ... } ⇒ void

This method returns an undefined value.

Provides iteration over added auto-requirements (see autobefore).

Yield Parameters:

  • type (String)

    the name of the type to autorequire an instance of

  • block (Proc)

    a block producing one or several dependencies to auto require (see autobefore).

Yield Returns:

  • (void)

2148
2149
2150
2151
2152
2153
# File 'lib/puppet/type.rb', line 2148

def self.eachautobefore
  @autobefores ||= {}
  @autobefores.each { |type,block|
    yield(type, block)
  }
end

.eachautonotify {|type, block| ... } ⇒ void

This method returns an undefined value.

Provides iteration over added auto-requirements (see autonotify).

Yield Parameters:

  • type (String)

    the name of the type to autorequire an instance of

  • block (Proc)

    a block producing one or several dependencies to auto require (see autonotify).

Yield Returns:

  • (void)

2172
2173
2174
2175
2176
2177
# File 'lib/puppet/type.rb', line 2172

def self.eachautonotify
  @autonotifies ||= {}
  @autonotifies.each { |type,block|
    yield(type, block)
  }
end

.eachautorequire {|type, block| ... } ⇒ void

This method returns an undefined value.

Provides iteration over added auto-requirements (see autorequire).

Yield Parameters:

  • type (String)

    the name of the type to autorequire an instance of

  • block (Proc)

    a block producing one or several dependencies to auto require (see autorequire).

Yield Returns:

  • (void)

2136
2137
2138
2139
2140
2141
# File 'lib/puppet/type.rb', line 2136

def self.eachautorequire
  @autorequires ||= {}
  @autorequires.each { |type, block|
    yield(type, block)
  }
end

.eachautosubscribe {|type, block| ... } ⇒ void

This method returns an undefined value.

Provides iteration over added auto-requirements (see autosubscribe).

Yield Parameters:

  • type (String)

    the name of the type to autorequire an instance of

  • block (Proc)

    a block producing one or several dependencies to auto require (see autosubscribe).

Yield Returns:

  • (void)

2160
2161
2162
2163
2164
2165
# File 'lib/puppet/type.rb', line 2160

def self.eachautosubscribe
  @autosubscribes ||= {}
  @autosubscribes.each { |type,block|
    yield(type, block)
  }
end

.eachmetaparam {|p| ... } ⇒ void

This method returns an undefined value.

Provides iteration over meta-parameters.

Yield Parameters:


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

def self.eachmetaparam
  @@metaparams.each { |p| yield p.name }
end

.ensurablevoid .ensurable({|| ... }) ⇒ void

Note:

This method will be automatically called without a block if the type implements the methods specified by ensurable?. It is recommended to always call this method and not rely on this automatic specification to clearly state that the type is ensurable.

This method returns an undefined value.

Creates a new `ensure` property with configured default values or with configuration by an optional block. This method is a convenience method for creating a property `ensure` with default accepted values. If no block is specified, the new `ensure` property will accept the default symbolic values `:present`, and `:absent` - see Property::Ensure. If something else is wanted, pass a block and make calls to Property.newvalue from this block to define each possible value. If a block is passed, the defaults are not automatically added to the set of valid values.

Yields:

  • ()

    A block evaluated in scope of the new Parameter

Yield Returns:

  • (void)

215
216
217
218
219
220
221
222
223
# File 'lib/puppet/type.rb', line 215

def self.ensurable(&block)
  if block_given?
    self.newproperty(:ensure, :parent => Puppet::Property::Ensure, &block)
  else
    self.newproperty(:ensure, :parent => Puppet::Property::Ensure) do
      self.defaultvalues
    end
  end
end

.ensurable?Boolean

Returns true if the type implements the default behavior expected by being ensurable “by default”. A type is ensurable by default if it responds to `:exists`, `:create`, and `:destroy`. If a type implements these methods and have not already specified that it is ensurable, it will be made so with the defaults specified in ensurable.

Returns:

  • (Boolean)

    whether the type is ensurable or not.


231
232
233
234
235
236
237
# File 'lib/puppet/type.rb', line 231

def self.ensurable?
  # If the class has all three of these methods defined, then it's
  # ensurable.
  [:exists?, :create, :destroy].all? { |method|
    self.public_method_defined?(method)
  }
end

.handle_param_options(name, options) ⇒ void

This method returns an undefined value.

Processes the options for a named parameter.

Parameters:

  • name (String)

    the name of a parameter

  • options (Hash)

    a hash of options

Options Hash (options):

  • :boolean (Boolean)

    if option set to true, an access method on the form name? is added for the param


293
294
295
296
297
298
299
300
301
302
303
# File 'lib/puppet/type.rb', line 293

def self.handle_param_options(name, options)
  # If it's a boolean parameter, create a method to test the value easily
  if options[:boolean]
    define_method(name.to_s + "?") do
      val = self[name]
      if val == :true or val == true
        return true
      end
    end
  end
end

.hash2resource(hash) ⇒ Puppet::Resource

TODO:

as opposed to a complex hash? Other raised exceptions?

Converts a simple hash into a Resource instance.

Parameters:

  • hash (Hash{Symbol, String => Object})

    resource attribute to value map to initialize the created resource from

Returns:

Raises:


1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
# File 'lib/puppet/type.rb', line 1250

def self.hash2resource(hash)
  hash = hash.inject({}) { |result, ary| result[ary[0].to_sym] = ary[1]; result }

  title = hash.delete(:title)
  title ||= hash[:name]
  title ||= hash[key_attributes.first] if key_attributes.length == 1

  raise Puppet::Error, "Title or name must be provided" unless title

  # Now create our resource.
  resource = Puppet::Resource.new(self, title)
  resource.catalog = hash.delete(:catalog)

  sensitive = hash.delete(:sensitive_parameters)
  if sensitive
    resource.sensitive_parameters = sensitive
  end

  hash.each do |param, value|
    resource[param] = value
  end
  resource
end

.initvarsvoid

TODO:

Does the explanation make sense?

This method returns an undefined value.

Initializes all of the variables that must be initialized for each subclass.


2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
# File 'lib/puppet/type.rb', line 2309

def self.initvars
  # all of the instances of this class
  @objects = Hash.new
  @aliases = Hash.new

  @defaults = {}

  @parameters ||= []

  @validproperties = {}
  @properties = []
  @parameters = []
  @paramhash = {}

  @paramdoc = Hash.new { |hash,key|
    key = key.intern if key.is_a?(String)
    if hash.include?(key)
      hash[key]
    else
      "Param Documentation for #{key} not found"
    end
  }

  @doc ||= ""

end

.instancesObject

TODO:

Retrieves them from where? Known to whom?

Retrieves all known instances. Either requires providers or must be overridden.

Raises:

  • (Puppet::DevError)

    when there are no providers and the implementation has not overridden this method.


1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
# File 'lib/puppet/type.rb', line 1203

def self.instances
  raise Puppet::DevError, _("%{name} has no providers and has not overridden 'instances'") % { name: self.name } if provider_hash.empty?

  # Put the default provider first, then the rest of the suitable providers.
  provider_instances = {}
  providers_by_source.collect do |provider|
    provider.instances.collect do |instance|
      # We always want to use the "first" provider instance we find, unless the resource
      # is already managed and has a different provider set
      title = instance.respond_to?(:title) ? instance.title : instance.name
      other = provider_instances[title]
      if other
        Puppet.debug {
          "%s %s found in both %s and %s; skipping the %s version" % [self.name.to_s.capitalize, title, other.class.name, instance.class.name, instance.class.name]
        }
        next
      end
      provider_instances[title] = instance

      result = new(:name => instance.name, :provider => instance, :title => title)
      properties.each { |name| result.newattr(name) }
      result
    end
  end.flatten.compact
end

.is_capability?Boolean

Deprecated.

application orchestration will be removed in puppet 7

Returns:

  • (Boolean)

123
124
125
126
# File 'lib/puppet/type.rb', line 123

def is_capability?
  c = is_capability
  c.nil? ? false : c
end

.isomorphic?Boolean

Returns true if the type's notion of name is the identity of a resource. See the overview of this class for a longer explanation of the concept isomorphism. Defaults to true.

Returns:

  • (Boolean)

    true, if this type's name is isomorphic with the object


939
940
941
942
943
944
945
# File 'lib/puppet/type.rb', line 939

def self.isomorphic?
  if defined?(@isomorphic)
    return @isomorphic
  else
    return true
  end
end

.key_attribute_parametersArray<Puppet::Parameter>

Returns the list of parameters that comprise the composite key / “uniqueness key”. All parameters that return true from #isnamevar? or is named `:name` are included in the returned result.

Returns:

See Also:


386
387
388
389
390
391
392
# File 'lib/puppet/type.rb', line 386

def self.key_attribute_parameters
  @key_attribute_parameters ||= (
    @parameters.find_all { |param|
      param.isnamevar? or param.name == :name
    }
  )
end

.key_attributesArray<String>

Returns cached key_attribute_parameters names. Key attributes are properties and parameters that comprise a composite key or “uniqueness key”.

Returns:

  • (Array<String>)

    cached key_attribute names


399
400
401
402
# File 'lib/puppet/type.rb', line 399

def self.key_attributes
  # This is a cache miss around 0.05 percent of the time. --daniel 2012-07-17
  @key_attributes_cache ||= key_attribute_parameters.collect { |p| p.name }
end

.metaparam?(param) ⇒ Boolean

Is the given parameter a meta-parameter?

Returns:

  • (Boolean)

    true if the given parameter is a meta-parameter.


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

def self.metaparam?(param)
  @@metaparamhash.include?(param.intern)
end

.metaparamclass(name) ⇒ Class?

Returns the meta-parameter class associated with the given meta-parameter name. Accepts a `nil` name, and return nil.

Parameters:

  • name (String, nil)

    the name of a meta-parameter

Returns:

  • (Class, nil)

    the class for the given meta-parameter, or `nil` if no such meta-parameter exists, (or if the given meta-parameter name is `nil`.


318
319
320
321
# File 'lib/puppet/type.rb', line 318

def self.metaparamclass(name)
  return nil if name.nil?
  @@metaparamhash[name.intern]
end

.metaparamdoc(metaparam) ⇒ String

Returns the documentation for a given meta-parameter of this type.

Parameters:

Returns:

  • (String)

    the documentation associated with the given meta-parameter, or nil of no such documentation exists.

Raises:

  • if the given metaparam is not a meta-parameter in this type


336
337
338
# File 'lib/puppet/type.rb', line 336

def self.metaparamdoc(metaparam)
  @@metaparamhash[metaparam].doc
end

.metaparamsArray<String>

Returns all meta-parameter names.

Returns:

  • (Array<String>)

    all meta-parameter names


326
327
328
# File 'lib/puppet/type.rb', line 326

def self.metaparams
  @@metaparams.collect { |param| param.name }
end

.needs_ensure_retrievedObject

Says if the ensure property should be retrieved if the resource is ensurable Defaults to true. Some resource type classes can override it


1091
1092
1093
# File 'lib/puppet/type.rb', line 1091

def self.needs_ensure_retrieved
  true
end

.newmetaparam(name, options = {}) {|| ... } ⇒ Class<inherits Puppet::Parameter>

TODO:

Verify that this description is ok

Creates a new meta-parameter. This creates a new meta-parameter that is added to this and all inheriting types.

Parameters:

  • name (Symbol)

    the name of the parameter

  • options (Hash) (defaults to: {})

    a hash with options.

Options Hash (options):

  • :parent (Class<inherits Puppet::Parameter>) — default: Puppet::Parameter

    the super class of this parameter

  • :attributes (Hash{String => Object})

    a hash that is applied to the generated class by calling setter methods corresponding to this hash's keys/value pairs. This is done before the given block is evaluated.

  • :boolean (Boolean) — default: false

    specifies if this is a boolean parameter

  • :namevar (Boolean) — default: false

    specifies if this parameter is the namevar

  • :required_features (Symbol, Array<Symbol>)

    specifies required provider features by name

Yields:

  • ()

    a required block that is evaluated in the scope of the new meta-parameter

Returns:


357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/puppet/type.rb', line 357

def self.newmetaparam(name, options = {}, &block)
  @@metaparams ||= []
  @@metaparamhash ||= {}
  name = name.intern

  param = genclass(
    name,
    :parent => options[:parent] || Puppet::Parameter,
    :prefix => "MetaParam",
    :hash => @@metaparamhash,
    :array => @@metaparams,
    :attributes => options[:attributes],
    &block
  )

  # Grr.
  param.required_features = options[:required_features] if options[:required_features]

  handle_param_options(name, options)

  param.metaparam = true

  param
end

.newparam(name, options = {}) {|| ... } ⇒ Class<inherits Puppet::Parameter>

Creates a new parameter.

Parameters:

  • name (Symbol)

    the name of the parameter

  • options (Hash) (defaults to: {})

    a hash with options.

Options Hash (options):

  • :parent (Class<inherits Puppet::Parameter>) — default: Puppet::Parameter

    the super class of this parameter

  • :attributes (Hash{String => Object})

    a hash that is applied to the generated class by calling setter methods corresponding to this hash's keys/value pairs. This is done before the given block is evaluated.

  • :boolean (Boolean) — default: false

    specifies if this is a boolean parameter

  • :namevar (Boolean) — default: false

    specifies if this parameter is the namevar

  • :required_features (Symbol, Array<Symbol>)

    specifies required provider features by name

Yields:

  • ()

    a required block that is evaluated in the scope of the new parameter

Returns:


472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# File 'lib/puppet/type.rb', line 472

def self.newparam(name, options = {}, &block)
  options[:attributes] ||= {}

  param = genclass(
    name,
    :parent     => options[:parent] || Puppet::Parameter,
    :attributes => options[:attributes],
    :block      => block,
    :prefix     => "Parameter",
    :array      => @parameters,
    :hash       => @paramhash
  )

  handle_param_options(name, options)

  # Grr.
  param.required_features = options[:required_features] if options[:required_features]

  param.isnamevar if options[:namevar]

  param
end

.newproperty(name, options = {}) {|| ... } ⇒ Class<inherits Puppet::Property>

Creates a new property.

Parameters:

  • name (Symbol)

    the name of the property

  • options (Hash) (defaults to: {})

    a hash with options.

Options Hash (options):

  • :array_matching (Symbol) — default: :first

    specifies how the current state is matched against the wanted state. Use `:first` if the property is single valued, and (`:all`) otherwise.

  • :parent (Class<inherits Puppet::Property>) — default: Puppet::Property

    the super class of this property

  • :attributes (Hash{String => Object})

    a hash that is applied to the generated class by calling setter methods corresponding to this hash's keys/value pairs. This is done before the given block is evaluated.

  • :boolean (Boolean) — default: false

    specifies if this is a boolean parameter

  • :retrieve (Symbol)

    the method to call on the provider (or `parent` if `provider` is not set) to retrieve the current value of this property.

  • :required_features (Symbol, Array<Symbol>)

    specifies required provider features by name

Yields:

  • ()

    a required block that is evaluated in the scope of the new property

Returns:

Raises:


513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/puppet/type.rb', line 513

def self.newproperty(name, options = {}, &block)
  name = name.intern

  # This is here for types that might still have the old method of defining
  # a parent class.
  unless options.is_a? Hash
    raise Puppet::DevError, _("Options must be a hash, not %{type}") % { type: options.inspect }
  end

  raise Puppet::DevError, _("Class %{class_name} already has a property named %{property}") % { class_name: self.name, property: name } if @validproperties.include?(name)

  parent = options[:parent]
  if parent
    options.delete(:parent)
  else
    parent = Puppet::Property
  end

  # We have to create our own, new block here because we want to define
  # an initial :retrieve method, if told to, and then eval the passed
  # block if available.
  prop = genclass(name, :parent => parent, :hash => @validproperties, :attributes => options) do
    # If they've passed a retrieve method, then override the retrieve
    # method on the class.
    if options[:retrieve]
      define_method(:retrieve) do
        provider.send(options[:retrieve])
      end
    end

    class_eval(&block) if block
  end

  # If it's the 'ensure' property, always put it first.
  if name == :ensure
    @properties.unshift prop
  else
    @properties << prop
  end

  prop
end

.paramclass(name) ⇒ Puppet::Parameter

Returns the parameter class associated with the given parameter name.

Returns:

  • (Puppet::Parameter)

    Returns the parameter class associated with the given parameter name.


567
568
569
# File 'lib/puppet/type.rb', line 567

def self.paramclass(name)
  @paramhash[name]
end

.paramdoc(param) ⇒ Object


556
557
558
# File 'lib/puppet/type.rb', line 556

def self.paramdoc(param)
  @paramhash[param].doc
end

.parametersArray<String>

Returns the parameter names

Returns:

  • (Array<String>)

    Returns the parameter names


561
562
563
564
# File 'lib/puppet/type.rb', line 561

def self.parameters
  return [] unless defined?(@parameters)
  @parameters.collect { |klass| klass.name }
end

.parameters_to_includeArray<Symbol>

Returns any parameters that should be included by default in puppet resource's output

Returns:

  • (Array<Symbol>)

    the parameters to include


406
407
408
# File 'lib/puppet/type.rb', line 406

def self.parameters_to_include
  []
end

.propertybyname(name) ⇒ Puppet::Property

Returns the property class ??? associated with the given property name

Returns:

  • (Puppet::Property)

    Returns the property class ??? associated with the given property name


572
573
574
# File 'lib/puppet/type.rb', line 572

def self.propertybyname(name)
  @validproperties[name]
end

.provide(name, options = {}, &block) ⇒ Puppet::Provider

TODO:

Fix Confusing Explanations! Is this a new provider of a Type (metatype), or a provider of an instance of Type (a resource), or a Provider (the implementation of a Type's behavior). CONFUSED. It calls magically named methods like “providify” …

Creates a new provider of a type. This method must be called directly on the type that it's implementing.

Parameters:

  • name (String, Symbol)

    the name of the WHAT? provider? type?

  • options (Hash{Symbol => Object}) (defaults to: {})

    a hash of options, used by this method, and passed on to Util::ClassGen#genclass, (see it for additional options to pass).

Options Hash (options):

  • :parent (Puppet::Provider)

    the parent provider (what is this?)

  • :resource_type (Puppet::Type)

    the resource type, defaults to this type if unspecified

Returns:

Raises:


1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
# File 'lib/puppet/type.rb', line 1895

def self.provide(name, options = {}, &block)
  name = name.intern

  if unprovide(name)
    Puppet.debug { "Reloading #{name} #{self.name} provider" }
  end

  pname = options[:parent]
  parent = if pname
    options.delete(:parent)
    if pname.is_a? Class
      pname
    else
      provider = self.provider(pname)
      if provider
        provider
      else
        raise Puppet::DevError, _("Could not find parent provider %{parent} of %{name}") % { parent: pname, name: name }
      end
    end
  else
    Puppet::Provider
  end

  options[:resource_type] ||= self

  self.providify

  provider = genclass(
    name,
    :parent     => parent,
    :hash       => provider_hash,
    :prefix     => "Provider",
    :block      => block,
    :include    => feature_module,
    :extend     => feature_module,
    :attributes => options
  )

  provider
end

.provider(name) ⇒ Puppet::Provider?

Returns the provider having the given name. This will load a provider if it is not already loaded. The returned provider is the first found provider having the given name, where “first found” semantics is defined by the providerloader in use.

Parameters:

  • name (String)

    the name of the provider to get

Returns:

  • (Puppet::Provider, nil)

    the found provider, or nil if no provider of the given name was found


1852
1853
1854
1855
1856
1857
1858
# File 'lib/puppet/type.rb', line 1852

def self.provider(name)
  name = name.intern

  # If we don't have it yet, try loading it.
  @providerloader.load(name, Puppet.lookup(:current_environment)) unless provider_hash.has_key?(name)
  provider_hash[name]
end

.provider_hashHash{ ??? => Puppet::Provider}

Returns a hash of WHAT EXACTLY for this type.

Returns:

  • (Hash{ ??? => Puppet::Provider})

    Returns a hash of WHAT EXACTLY for this type.

See Also:


1841
1842
1843
# File 'lib/puppet/type.rb', line 1841

def self.provider_hash
  Puppet::Type.provider_hash_by_type(self.name)
end

.provider_hash_by_type(type) ⇒ Hash{??? => Puppet::Provider}

TODO:

what goes into this hash?

Returns a hash of WHAT EXACTLY for the given type

Returns:

  • (Hash{??? => Puppet::Provider})

    Returns a hash of WHAT EXACTLY for the given type


1834
1835
1836
1837
# File 'lib/puppet/type.rb', line 1834

def self.provider_hash_by_type(type)
  @provider_hashes ||= {}
  @provider_hashes[type] ||= {}
end

.providersArray<String>

Returns a list of loaded providers by name. This method will not load/search for available providers.

Returns:

  • (Array<String>)

    list of loaded provider names


1864
1865
1866
# File 'lib/puppet/type.rb', line 1864

def self.providers
  provider_hash.keys
end

.providers_by_sourceArray<Puppet::Provider>

TODO:

Needs better explanation; what does “source” mean in this context?

Returns a list of one suitable provider per source, with the default provider first.

Returns:


1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
# File 'lib/puppet/type.rb', line 1233

def self.providers_by_source
  # Put the default provider first (can be nil), then the rest of the suitable providers.
  sources = []
  [defaultprovider, suitableprovider].flatten.uniq.collect do |provider|
    next if provider.nil?
    next if sources.include?(provider.source)

    sources << provider.source
    provider
  end.compact
end

.providifyvoid

This method returns an undefined value.

Ensures there is a `:provider` parameter defined. Should only be called if there are providers.


1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
# File 'lib/puppet/type.rb', line 1940

def self.providify
  return if @paramhash.has_key? :provider

  param = newparam(:provider) do
    # We're using a hacky way to get the name of our type, since there doesn't
    # seem to be a correct way to introspect this at the time this code is run.
    # We expect that the class in which this code is executed will be something
    # like Puppet::Type::Ssh_authorized_key::ParameterProvider.
    desc <<-EOT
      The specific backend to use for this `#{self.to_s.split('::')[2].downcase}`
      resource. You will seldom need to specify this --- Puppet will usually
      discover the appropriate provider for your platform.
    EOT

    # This is so we can refer back to the type to get a list of
    # providers for documentation.
    class << self
      # The reference to a parent type for the parameter `:provider` used to get a list of
      # providers for documentation purposes.
      #
      attr_accessor :parenttype
    end

    # Provides the ability to add documentation to a provider.
    #
    def self.doc
      # Since we're mixing @doc with text from other sources, we must normalize
      # its indentation with scrub. But we don't need to manually scrub the
      # provider's doc string, since markdown_definitionlist sanitizes its inputs.
      scrub(@doc) + "Available providers are:\n\n" + parenttype.providers.sort_by(&:to_s).collect { |i|
        markdown_definitionlist( i, scrub(parenttype().provider(i).doc) )
      }.join
    end

    # For each resource, the provider param defaults to
    # the type's default provider
    defaultto {
      prov = @resource.class.defaultprovider
      prov.name if prov
    }

    validate do |provider_class|
      provider_class = provider_class[0] if provider_class.is_a? Array
      provider_class = provider_class.class.name if provider_class.is_a?(Puppet::Provider)

      unless @resource.class.provider(provider_class)
        raise ArgumentError, _("Invalid %{resource} provider '%{provider_class}'") % { resource: @resource.class.name, provider_class: provider_class}
      end
    end

    munge do |provider|
      provider = provider[0] if provider.is_a? Array
      provider = provider.intern if provider.is_a? String
      @resource.provider = provider

      if provider.is_a?(Puppet::Provider)
        provider.class.name
      else
        provider
      end
    end
  end
  param.parenttype = self
end

.relationship_paramsObject

TODO:

document this, have no clue what this does… it returns “RelationshipMetaparam.subclasses”


1622
1623
1624
# File 'lib/puppet/type.rb', line 1622

def self.relationship_params
  RelationshipMetaparam.subclasses
end

.suitableproviderArray<Puppet::Provider>

Note:

This method also does some special processing which rejects a provider named `:fake` (for testing purposes).

Returns a list of suitable providers for the given type. A call to this method will load all providers if not already loaded and ask each if it is suitable - those that are are included in the result.

Returns:


2022
2023
2024
2025
2026
2027
2028
2029
# File 'lib/puppet/type.rb', line 2022

def self.suitableprovider
  providerloader.loadall(Puppet.lookup(:current_environment)) if provider_hash.empty?
  provider_hash.find_all { |name, provider|
    provider.suitable?
  }.collect { |name, provider|
    provider
  }.reject { |p| p.name == :fake } # For testing
end

.title_patternsArray<Array<Regexp, Array<Array <Symbol, Proc>>>>?

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.

Note:

Advanced: some logic requires this mapping to be done differently, using a different validation/pattern, breaking up the title into several parts assigning each to an individual attribute, or even use a composite identity where all namevars are seen as part of the unique identity (such computation is done by the #uniqueness method. These advanced options are rarely used (only one of the built in puppet types use this, and then only a small part of the available functionality), and the support for these advanced mappings is not implemented in a straight forward way. For these reasons, this method has been marked as private).

Returns a mapping from the title string to setting of attribute values. This default implementation provides a mapping of title to the one and only namevar present in the type's definition.

Returns:

  • (Array<Array<Regexp, Array<Array <Symbol, Proc>>>>, nil)

    a structure with a regexp and the first key_attribute ???

Raises:

  • (Puppet::DevError)

    if there is no title pattern and there are two or more key attributes


438
439
440
441
442
443
444
445
446
# File 'lib/puppet/type.rb', line 438

def self.title_patterns
  case key_attributes.length
  when 0; []
  when 1;
    [ [ /(.*)/m, [ [key_attributes.first] ] ] ]
  else
    raise Puppet::DevError, _("you must specify title patterns when there are two or more key attributes")
  end
end

.to_sString

Returns the name of this type (if specified) or the parent type #to_s. The returned name is on the form “Puppet::Type::<name>”, where the first letter of name is capitalized.

Returns:

  • (String)

    the fully qualified name Puppet::Type::<name> where the first letter of name is capitalized


2341
2342
2343
2344
2345
2346
2347
# File 'lib/puppet/type.rb', line 2341

def self.to_s
  if defined?(@name)
    "Puppet::Type::#{@name.to_s.capitalize}"
  else
    super
  end
end

.unprovide(name) ⇒ Object

TODO:

this needs a better explanation

Removes the implementation class of a given provider.

Returns:


2008
2009
2010
2011
2012
2013
2014
# File 'lib/puppet/type.rb', line 2008

def self.unprovide(name)
  if @defaultprovider and @defaultprovider.name == name
    @defaultprovider = nil
  end

  rmclass(name, :hash => provider_hash, :prefix => "Provider")
end

.valid_parameter?(name) ⇒ Boolean

Note:

see comment in code - how should this be documented? Are some of the other query methods deprecated? (or should be).

Returns whether or not the given name is the name of a property, parameter or meta-parameter

Returns:

  • (Boolean)

    true if the given attribute name is the name of an existing property, parameter or meta-parameter


617
618
619
# File 'lib/puppet/type.rb', line 617

def self.valid_parameter?(name)
  validattr?(name)
end

.validate {|| ... } ⇒ void

This method returns an undefined value.

Creates a `validate` method that is used to validate a resource before it is operated on. The validation should raise exceptions if the validation finds errors. (It is not recommended to issue warnings as this typically just ends up in a logfile - you should fail if a validation fails). The easiest way to raise an appropriate exception is to call the method Util::Errors.fail with the message as an argument.

Yields:

  • ()

    a required block called with self set to the instance of a Type class representing a resource.


2360
2361
2362
# File 'lib/puppet/type.rb', line 2360

def self.validate(&block)
  define_method(:validate, &block)
end

.validattr?(name) ⇒ Boolean

Returns whether or not the given name is the name of a property, parameter or meta-parameter

Returns:

  • (Boolean)

    true if the given attribute name is the name of an existing property, parameter or meta-parameter


579
580
581
582
583
584
585
586
587
588
589
# File 'lib/puppet/type.rb', line 579

def self.validattr?(name)
  name = name.intern
  return true if name == :name
  @validattrs ||= {}

  unless @validattrs.include?(name)
    @validattrs[name] = !!(self.validproperty?(name) or self.validparameter?(name) or self.metaparam?(name))
  end

  @validattrs[name]
end

.validparameter?(name) ⇒ Boolean

Returns true if the given name is the name of an existing parameter

Returns:

  • (Boolean)

    Returns true if the given name is the name of an existing parameter

Raises:


608
609
610
611
# File 'lib/puppet/type.rb', line 608

def self.validparameter?(name)
  raise Puppet::DevError, _("Class %{class_name} has not defined parameters") % { class_name: self } unless defined?(@parameters)
  !!(@paramhash.include?(name) or @@metaparamhash.include?(name))
end

.validpropertiesArray<Symbol>, {}

TODO:

An empty hash is returned if there are no defined parameters (not an empty array). This looks like a bug.

Returns a list of valid property names, or an empty hash if there are none.

Returns:

  • (Array<Symbol>, {})

    Returns a list of valid property names, or an empty hash if there are none.


601
602
603
604
605
# File 'lib/puppet/type.rb', line 601

def self.validproperties
  return {} unless defined?(@parameters)

  @validproperties.keys
end

.validproperty?(name) ⇒ Boolean

Returns true if the given name is the name of an existing property

Returns:

  • (Boolean)

    Returns true if the given name is the name of an existing property


592
593
594
595
# File 'lib/puppet/type.rb', line 592

def self.validproperty?(name)
  name = name.intern
  @validproperties.include?(name) && @validproperties[name]
end

.validprovider?(name) ⇒ Boolean

TODO:

How does the provider know if it is suitable for the type? Is it just suitable for the platform/ environment where this method is executing?

Returns true if the given name is a reference to a provider and if this is a suitable provider for this type.

Parameters:

  • name (String)

    the name of the provider for which validity is checked

Returns:

  • (Boolean)

    true if the given name references a provider that is suitable


1875
1876
1877
1878
1879
# File 'lib/puppet/type.rb', line 1875

def self.validprovider?(name)
  name = name.intern

  (provider_hash.has_key?(name) && provider_hash[name].suitable?)
end

Instance Method Details

#<=>(other) ⇒ -1, ...

Compares this type against the given other (type) and returns -1, 0, or +1 depending on the order.

Parameters:

  • other (Object)

    the object to compare against (produces nil, if not kind of Type}

Returns:

  • (-1, 0, +1, nil)

    produces -1 if this type is before the given other type, 0 if equals, and 1 if after. Returns nil, if the given other is not a kind of Type.

See Also:

  • Comparable

99
100
101
102
103
104
105
# File 'lib/puppet/type.rb', line 99

def <=>(other)
  # Order is only maintained against other types, not arbitrary objects.
  # The natural order is based on the reference name used when comparing
  return nil unless other.is_a?(Puppet::CompilableResourceType) || other.class.is_a?(Puppet::CompilableResourceType)
  # against other type instances.
  self.ref <=> other.ref
end

#[](name) ⇒ Object

Gets the 'should' (wanted state) value of a parameter or property by name. To explicitly get the 'is' (current state) value use `o.is(:name)`, and to explicitly get the 'should' value use `o.should(:name)`

Parameters:

  • name (String)

    the name of the attribute to obtain the 'should' value for.

Returns:

  • (Object)

    'should'/wanted value of the given attribute


654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'lib/puppet/type.rb', line 654

def [](name)
  name = name.intern
  fail("Invalid parameter #{name}(#{name.inspect})") unless self.class.validattr?(name)

  if name == :name
    nv = name_var
    name = nv if nv
  end

  obj = @parameters[name]
  if obj
    # Note that if this is a property, then the value is the "should" value,
    # not the current value.
    obj.value
  else
    return nil
  end
end

#[]=(name, value) ⇒ Object

Sets the 'should' (wanted state) value of a property, or the value of a parameter.

Returns:

Raises:

  • (Puppet::Error)

    if the setting of the value fails, or if the given name is nil.

  • (Puppet::ResourceError)

    when the parameter validation raises Puppet::Error or ArgumentError


678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
# File 'lib/puppet/type.rb', line 678

def []=(name,value)
  name = name.intern

  fail("no parameter named '#{name}'") unless self.class.validattr?(name)

  if name == :name
    nv = name_var
    name = nv if nv
  end
  raise Puppet::Error.new("Got nil value for #{name}") if value.nil?

  property = self.newattr(name)

  if property
    begin
      # make sure the parameter doesn't have any errors
      property.value = value
    rescue Puppet::Error, ArgumentError => detail
      error = Puppet::ResourceError.new(_("Parameter %{name} failed on %{ref}: %{detail}") %
                                            { name: name, ref: ref, detail: detail })
      adderrorcontext(error, detail)
      raise error
    end
  end

  nil
end

#add_property_parameter(prop_name) ⇒ Boolean

Creates a new property value holder for the resource if it is valid and does not already exist

Returns:

  • (Boolean)

    true if a new parameter was added, false otherwise


628
629
630
631
632
633
634
# File 'lib/puppet/type.rb', line 628

def add_property_parameter(prop_name)
  if self.class.validproperty?(prop_name) && !@parameters[prop_name]
    self.newattr(prop_name)
    return true
  end
  false
end

#ancestorsArray<???>

TODO:

WHAT IS THIS ?

Returns the ancestors - WHAT? This implementation always returns an empty list.

Returns:

  • (Array<???>)

    returns a list of ancestors.


1018
1019
1020
# File 'lib/puppet/type.rb', line 1018

def ancestors
  []
end

#appliable_to_device?Boolean

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 true if a resource of this type can be evaluated on a 'network device' kind of hosts.

Returns:

  • (Boolean)

    Returns whether the resource is applicable to `:device`


2714
2715
2716
# File 'lib/puppet/type.rb', line 2714

def appliable_to_device?
  self.class.can_apply_to(:device)
end

#appliable_to_host?Boolean

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 true if a resource of this type can be evaluated on a regular generalized computer (ie not an appliance like a network device)

Returns:

  • (Boolean)

    Returns whether the resource is applicable to `:host`


2721
2722
2723
# File 'lib/puppet/type.rb', line 2721

def appliable_to_host?
  self.class.can_apply_to(:host)
end

#autobefore(rel_catalog = nil) ⇒ Object


2229
2230
2231
# File 'lib/puppet/type.rb', line 2229

def autobefore(rel_catalog = nil)
  autorelation(:before, rel_catalog)
end

#autonotify(rel_catalog = nil) ⇒ Object


2237
2238
2239
# File 'lib/puppet/type.rb', line 2237

def autonotify(rel_catalog = nil)
  autorelation(:notify, rel_catalog)
end

#autorelation(rel_type, rel_catalog = nil) ⇒ Object

TODO:

needs details - see the param rel_catalog, and type of this param

Adds dependencies to the catalog from added autorelations. See autorequire for how to add an auto-requirement.

Parameters:

  • rel_catalog (Puppet::Resource::Catalog, nil) (defaults to: nil)

    the catalog to add dependencies to. Defaults to the current catalog (set when the type instance was added to a catalog)

Raises:


2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
# File 'lib/puppet/type.rb', line 2187

def autorelation(rel_type, rel_catalog = nil)
  rel_catalog ||= catalog
  raise Puppet::DevError, _("You cannot add relationships without a catalog") unless rel_catalog

  reqs = []

  auto_rel = "eachauto#{rel_type}".to_sym

  self.class.send(auto_rel) { |type, block|
    # Ignore any types we can't find, although that would be a bit odd.
    next unless Puppet::Type.type(type)

    # Retrieve the list of names from the block.
    list = self.instance_eval(&block)
    next unless list
    list = [list] unless list.is_a?(Array)

    # Collect the current prereqs
    list.each { |dep|
      next if dep.nil?

      # Support them passing objects directly, to save some effort.
      unless dep.is_a?(Puppet::Type)
        # Skip autorelation that we aren't managing
        dep = rel_catalog.resource(type, dep)
        next unless dep
      end

      if [:require, :subscribe].include?(rel_type)
        reqs << Puppet::Relationship.new(dep, self)
      else
        reqs << Puppet::Relationship.new(self, dep)
      end
    }
  }
  reqs
end

#autorequire(rel_catalog = nil) ⇒ Object


2225
2226
2227
# File 'lib/puppet/type.rb', line 2225

def autorequire(rel_catalog = nil)
  autorelation(:require, rel_catalog)
end

#autosubscribe(rel_catalog = nil) ⇒ Object


2233
2234
2235
# File 'lib/puppet/type.rb', line 2233

def autosubscribe(rel_catalog = nil)
  autorelation(:subscribe, rel_catalog)
end

#builddependsArray<Puppet::Relationship>

Builds the dependencies associated with this resource.

Returns:


2244
2245
2246
2247
2248
2249
2250
# File 'lib/puppet/type.rb', line 2244

def builddepends
  # Handle the requires
  self.class.relationship_params.collect do |klass|
    param = @parameters[klass.name]
    param.to_edges if param
  end.flatten.reject { |r| r.nil? }
end

#currentpropvaluesHash{Puppet::Property => Object}

Returns a hash of the current properties and their values. If a resource is absent, its value is the symbol `:absent`

Returns:


1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
# File 'lib/puppet/type.rb', line 1159

def currentpropvalues
  # It's important to use the 'properties' method here, as it follows the order
  # in which they're defined in the class.  It also guarantees that 'ensure'
  # is the first property, which is important for skipping 'retrieve' on
  # all the properties if the resource is absent.
  ensure_state = false
  return properties.inject({}) do | prophash, property|
    if property.name == :ensure
      ensure_state = property.retrieve
      prophash[property] = ensure_state
    else
      if ensure_state == :absent
        prophash[property] = :absent
      else
        prophash[property] = property.retrieve
      end
    end
    prophash
  end
end

#delete(attr) ⇒ Object

TODO:

Don't know what the attr is (name or Property/Parameter?). Guessing it is a String name…

TODO:

Is it possible to delete a meta-parameter?

TODO:

What does delete mean? Is it deleted from the type or is its value state 'is'/'should' deleted?

Removes an attribute from the object; useful in testing or in cleanup when an error has been encountered

Parameters:

  • attr (String)

    the attribute to delete from this object. WHAT IS THE TYPE?

Raises:

  • (Puppet::DecError)

    when an attempt is made to delete an attribute that does not exists.


714
715
716
717
718
719
720
721
# File 'lib/puppet/type.rb', line 714

def delete(attr)
  attr = attr.intern
  if @parameters.has_key?(attr)
    @parameters.delete(attr)
  else
    raise Puppet::DevError.new(_("Undefined attribute '%{attribute}' in %{name}") % { attribute: attr, name: self})
  end
end

#deleting?Boolean

Returns true if the wanted state of the resource is that it should be absent (i.e. to be deleted).

Returns:

  • (Boolean)

    Returns true if the wanted state of the resource is that it should be absent (i.e. to be deleted).


622
623
624
# File 'lib/puppet/type.rb', line 622

def deleting?
  obj = @parameters[:ensure] and obj.should == :absent
end

#depthfirst?Boolean

TODO:

What is this used for?

Returns true if the search should be done in depth-first order. This implementation always returns false.

Returns:

  • (Boolean)

    true if the search should be done in depth first order.


987
988
989
# File 'lib/puppet/type.rb', line 987

def depthfirst?
  false
end

#eachparameter {|parameter| ... } ⇒ void

This method returns an undefined value.

Iterates over all parameters with value currently set.

Yield Parameters:


743
744
745
# File 'lib/puppet/type.rb', line 743

def eachparameter
  parameters_with_value.each { |parameter| yield parameter }
end

#eachproperty {|property| ... } ⇒ void

This method returns an undefined value.

Iterates over the properties that were set on this resource.

Yield Parameters:


726
727
728
729
730
731
# File 'lib/puppet/type.rb', line 726

def eachproperty
  # properties is a private method
  properties.each { |property|
    yield property
  }
end

#event(options = {}) ⇒ Puppet::Transaction::Event

TODO:

Needs a better explanation “Why should I care who is calling this method?”, What do I need to know about events and how they work? Where can I read about them?

Creates a transaction event. Called by Transaction or by a property. Merges the given options with the options `:resource`, `:file`, `:line`, and `:tags`, initialized from values in this object. For possible options to pass (if any ????) see Puppet::Transaction::Event.

Parameters:

  • options (Hash) (defaults to: {})

    options merged with a fixed set of options defined by this method, passed on to Puppet::Transaction::Event.

Returns:


755
756
757
# File 'lib/puppet/type.rb', line 755

def event(options = {})
  Puppet::Transaction::Event.new(**{:resource => self, :file => file, :line => line, :tags => tags}.merge(options))
end

#exported?Boolean

Returns whether the resource is exported or not

Returns:

  • (Boolean)

    Returns whether the resource is exported or not


2708
# File 'lib/puppet/type.rb', line 2708

def exported?; !!@exported; end

#finishArray<Puppet::Parameter>

TODO:

what is the expected sequence here - who is responsible for calling this? When? Is the returned type correct?

Finishes any outstanding processing. This method should be called as a final step in setup, to allow the parameters that have associated auto-require needs to be processed.

Returns:


2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
# File 'lib/puppet/type.rb', line 2575

def finish
  # Call post_compile hook on every parameter that implements it. This includes all subclasses
  # of parameter including, but not limited to, regular parameters, metaparameters, relationship
  # parameters, and properties.
  eachparameter do |parameter|
    parameter.post_compile if parameter.respond_to? :post_compile
  end

  # Make sure all of our relationships are valid.  Again, must be done
  # when the entire catalog is instantiated.
  self.class.relationship_params.collect do |klass|
    param = @parameters[klass.name]
    param.validate_relationship if param
  end.flatten.reject { |r| r.nil? }
end

#flush????

TODO:

What does Flushing the provider mean? Why is it interesting to know that this is called by the transaction? (It is not explained anywhere what a transaction is).

Flushes the provider if supported by the provider, else no action. This is called by the transaction.

Returns:

  • (???, nil)

    WHAT DOES IT RETURN? GUESS IS VOID


1044
1045
1046
# File 'lib/puppet/type.rb', line 1044

def flush
  self.provider.flush if self.provider and self.provider.respond_to?(:flush)
end

#insync?(is) ⇒ Boolean

TODO:

“contained in what?” in the given “in” parameter?

TODO:

deal with the comment _“FIXME I don't think this is used on the type instances any more, it's really only used for testing”_

Returns true if all contained objects are in sync.

Returns:

  • (Boolean)

    true if in sync, false otherwise.


1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
# File 'lib/puppet/type.rb', line 1055

def insync?(is)
  insync = true

  property = @parameters[:ensure]
  if property
    unless is.include? property
      #TRANSLATORS 'is' is a variable name and should not be translated
      raise Puppet::DevError, _("The 'is' value is not in the 'is' array for '%{name}'") % { name: property.name }
    end
    ensureis = is[property]
    if property.safe_insync?(ensureis) and property.should == :absent
      return true
    end
  end

  properties.each { |prop|
    unless is.include? prop
      #TRANSLATORS 'is' is a variable name and should not be translated
      raise Puppet::DevError, _("The 'is' value is not in the 'is' array for '%{name}'") % { name: prop.name }
    end

    propis = is[prop]
    unless prop.safe_insync?(propis)
      prop.debug("Not in sync: #{propis.inspect} vs #{prop.should.inspect}")
      insync = false
    #else
    #    property.debug("In sync")
    end
  }

  #self.debug("#{self} sync status is #{insync}")
  insync
end

#isomorphic?Boolean

TODO:

check that this gets documentation (it is at the class level as well as instance).

(see isomorphic?)

Returns:

  • (Boolean)

949
950
951
# File 'lib/puppet/type.rb', line 949

def isomorphic?
  self.class.isomorphic?
end

#log(msg) ⇒ void

This method returns an undefined value.

Creates a log entry with the given message at the log level specified by the parameter `loglevel`


2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
# File 'lib/puppet/type.rb', line 2384

def log(msg)

  Puppet::Util::Log.create(

    :level => @parameters[:loglevel].value,
    :message => msg,

    :source => self
  )
end

#managed?Boolean

Note:

An object that is managed always stays managed, but an object that is not managed may become managed later in its lifecycle.

Returns true if the instance is a managed instance. A 'yes' here means that the instance was created from the language, vs. being created in order resolve other questions, such as finding a package in a list.

Returns:

  • (Boolean)

    true if the object is managed


959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
# File 'lib/puppet/type.rb', line 959

def managed?
  # Once an object is managed, it always stays managed; but an object
  # that is listed as unmanaged might become managed later in the process,
  # so we have to check that every time
  if @managed
    return @managed
  else
    @managed = false
    properties.each { |property|
      s = property.should
      if s and ! property.class.unmanaged
        @managed = true
        break
      end
    }
    return @managed
  end
end

#nameString

TODO:

There is a comment in source that this is not quite the same as ':title' and that a switch should be made…

Returns the resource's name

Returns:

  • (String)

    the name of a resource


2597
2598
2599
# File 'lib/puppet/type.rb', line 2597

def name
  self[:name]
end

#name_varSymbol, Boolean

Returns the name of the namevar if there is only one or false otherwise.

Returns:

  • (Symbol, Boolean)

    Returns the name of the namevar if there is only one or false otherwise.


643
644
645
646
647
# File 'lib/puppet/type.rb', line 643

def name_var
  return @name_var_cache unless @name_var_cache.nil?
  key_attributes = self.class.key_attributes
  @name_var_cache = (key_attributes.length == 1) && key_attributes.first
end

#newattr(name) ⇒ Object #newattr(klass) ⇒ Object

Registers an attribute to this resource type instance. Requires either the attribute name or class as its argument. This is a noop if the named property/parameter is not supported by this resource. Otherwise, an attribute instance is created and kept in this resource's parameters hash.

Overloads:

  • #newattr(name) ⇒ Object

    Parameters:

    • name (Symbol)

      symbolic name of the attribute

  • #newattr(klass) ⇒ Object

    Parameters:

    • klass (Class)

      a class supported as an attribute class, i.e. a subclass of Parameter or Property

Returns:

  • (Object)

    An instance of the named Parameter or Property class associated to this resource type instance, or nil if the attribute is not supported


783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
# File 'lib/puppet/type.rb', line 783

def newattr(name)
  if name.is_a?(Class)
    klass = name
    name = klass.name
  end

  klass = self.class.attrclass(name)
  unless klass
    raise Puppet::Error, "Resource type #{self.class.name} does not support parameter #{name}"
  end

  if provider and ! provider.class.supports_parameter?(klass)
    missing = klass.required_features.find_all { |f| ! provider.class.feature?(f) }
    debug "Provider %s does not support features %s; not managing attribute %s" % [provider.class.name, missing.join(", "), name]
    return nil
  end

  return @parameters[name] if @parameters.include?(name)

  @parameters[name] = klass.new(:resource => self)
end

#noop?Boolean

Returns the `noop` run mode status of this.

Returns:

  • (Boolean)

    true if running in noop mode.


1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
# File 'lib/puppet/type.rb', line 1182

def noop?
  # If we're not a host_config, we're almost certainly part of
  # Settings, and we want to ignore 'noop'
  return false if catalog and ! catalog.host_config?

  if defined?(@noop)
    @noop
  else
    Puppet[:noop]
  end
end

#parameter(name) ⇒ Object

Returns the value of this object's parameter given by name

Parameters:

  • name (String)

    the name of the parameter

Returns:


815
816
817
# File 'lib/puppet/type.rb', line 815

def parameter(name)
  @parameters[name.to_sym]
end

#parametersHash{String => Object}

Returns a shallow copy of this object's hash of attributes by name. Note that his not only comprises parameters, but also properties and metaparameters. Changes to the contained parameters will have an effect on the parameters of this type, but changes to the returned hash does not.

Returns:

  • (Hash{String => Object})

    a new hash being a shallow copy of the parameters map name to parameter


824
825
826
# File 'lib/puppet/type.rb', line 824

def parameters
  @parameters.dup
end

#parameters_with_valueArray<Puppet::Parameter>

Return the parameters, metaparams, and properties that have a value or were set by a default. Properties are included since they are a subclass of parameter.

Returns:


736
737
738
# File 'lib/puppet/type.rb', line 736

def parameters_with_value
  self.class.allattrs.collect { |attr| parameter(attr) }.compact
end

#parentPuppet::Type?

Returns the parent of this in the catalog. In case of an erroneous catalog where multiple parents have been produced, the first found (non deterministic) parent is returned.

Returns:

  • (Puppet::Type, nil)

    the containing resource or nil if there is no catalog or no containing resource.


2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
# File 'lib/puppet/type.rb', line 2607

def parent
  return nil unless catalog
  return @parent if @parent
  parents = catalog.adjacent(self, :direction => :in)
  @parent = if parents
    parents.shift
  else
    nil
  end
end

#pathString

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

Returns:

  • (String)

808
809
810
# File 'lib/puppet/type.rb', line 808

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.


1280
1281
1282
1283
1284
1285
1286
1287
# File 'lib/puppet/type.rb', line 1280

def pathbuilder
  p = parent
  if p
    [p.pathbuilder, self.ref].flatten
  else
    [self.ref]
  end
end

#pre_run_checkvoid

This method is abstract.

a resource type may implement this method to perform validation checks that can query the complete catalog

This method returns an undefined value.

Lifecycle method for a resource. This is called during graph creation. It should perform any consistency checking of the catalog and raise a Puppet::Error if the transaction should be aborted.

It differs from the validate method, since it is called later during initialization and can rely on self.catalog to have references to all resources that comprise the catalog.

Raises:

See Also:

  • Puppet::Transaction#add_vertex

1035
1036
# File 'lib/puppet/type.rb', line 1035

def pre_run_check
end

#present?(current_values) ⇒ Boolean

Given the hash of current properties, should this resource be treated as if it currently exists on the system. May need to be overridden by types that offer up more than just :absent and :present.

Returns:

  • (Boolean)

1151
1152
1153
# File 'lib/puppet/type.rb', line 1151

def present?(current_values)
  current_values[:ensure] != :absent
end

#propertiesArray<Puppet::Property>

TODO:

“what does the 'order specified in the class' mean? The order the properties where added in the ruby file adding a new type with new properties?

Returns all of the property objects, in the order specified in the class.

Returns:

  • (Array<Puppet::Property>)

    Returns all of the property objects, in the order specified in the class.


930
931
932
# File 'lib/puppet/type.rb', line 930

def properties
  self.class.properties.collect { |prop| @parameters[prop.name] }.compact
end

#property(name) ⇒ Puppet::Property

TODO:

LAK:NOTE(20081028) Since the 'parameter' method is now a superset of this method, this one should probably go away at some point. - Does this mean it should be deprecated ?

Returns a Property instance by name. To return the value, use 'resource'

Returns:

  • (Puppet::Property)

    the property with the given name, or nil if not a property or does not exist.


840
841
842
843
844
845
846
847
# File 'lib/puppet/type.rb', line 840

def property(name)
  obj = @parameters[name.intern]
  if obj && obj.is_a?(Puppet::Property)
    obj
  else
    nil
  end
end

#propertydefined?(name) ⇒ Boolean

Returns whether the attribute given by name has been added to this resource or not.

Returns:

  • (Boolean)

    Returns whether the attribute given by name has been added to this resource or not.


830
831
832
833
# File 'lib/puppet/type.rb', line 830

def propertydefined?(name)
  name = name.intern unless name.is_a? Symbol
  @parameters.include?(name)
end

#purgingObject

TODO:

what does this mean; “mark that we are purging” (purging what from where). How to use/when? Is this internal API in transactions?

Marks the object as “being purged”. This method is used by transactions to forbid deletion when there are dependencies.

See Also:


2640
2641
2642
# File 'lib/puppet/type.rb', line 2640

def purging
  @purging = true
end

#purging?Boolean

Returns whether this resource is being purged or not. This method is used by transactions to forbid deletion when there are dependencies.

Returns:

  • (Boolean)

    the current “purging” state


2648
2649
2650
2651
2652
2653
2654
# File 'lib/puppet/type.rb', line 2648

def purging?
  if defined?(@purging)
    @purging
  else
    false
  end
end

#refString

Returns a reference to this as a string in “Type” format.

Returns:

  • (String)

    a reference to this object on the form 'Type'


2621
2622
2623
2624
2625
# File 'lib/puppet/type.rb', line 2621

def ref
  # memoizing this is worthwhile ~ 3 percent of calls are the "first time
  # around" in an average run of Puppet. --daniel 2012-07-17
  @ref ||= "#{self.class.name.to_s.capitalize}[#{self.title}]"
end

#removevoid

TODO:

removes if from where?

This method returns an undefined value.

Removes this object (FROM WHERE?)


994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
# File 'lib/puppet/type.rb', line 994

def remove()
  # This is hackish (mmm, cut and paste), but it works for now, and it's
  # better than warnings.
  @parameters.each do |name, obj|
    obj.remove
  end
  @parameters.clear

  @parent = nil

  # Remove the reference to the provider.
  if self.provider
    @provider.clear
    @provider = nil
  end
end

#retrievePuppet::Resource

TODO:

As opposed to all non contained properties? How is this different than any of the other methods that also “gets” properties/parameters/etc. ?

Retrieves the current value of all contained properties. Parameters and meta-parameters are not included in the result.

Returns:

Raises:

  • (fail???)

    if there is a provider and it is not suitable for the host this is evaluated for.


1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
# File 'lib/puppet/type.rb', line 1101

def retrieve
  fail "Provider #{provider.class.name} is not functional on this host" if self.provider.is_a?(Puppet::Provider) and ! provider.class.suitable?

  result = Puppet::Resource.new(self.class, title)

  # Provide the name, so we know we'll always refer to a real thing
  result[:name] = self[:name] unless self[:name] == title

  ensure_prop = property(:ensure)
  if !ensure_prop && self.class.needs_ensure_retrieved && self.class.validattr?(:ensure)
    ensure_prop = newattr(:ensure)
  end

  if ensure_prop
    result[:ensure] = ensure_state = ensure_prop.retrieve
  else
    ensure_state = nil
  end

  properties.each do |property|
    next if property.name == :ensure
    if ensure_state == :absent
      result[property] = :absent
    else
      result[property] = property.retrieve
    end
  end

  result
end

#retrieve_resourcePuppet::Resource

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.

Retrieve the current state of the system as a Puppet::Resource. For the base Puppet::Type this does the same thing as #retrieve, but specific types are free to implement #retrieve as returning a hash, and this will call #retrieve and convert the hash to a resource. This is used when determining when syncing a resource.

Returns:

  • (Puppet::Resource)

    A resource representing the current state of the system.


1142
1143
1144
1145
1146
# File 'lib/puppet/type.rb', line 1142

def retrieve_resource
  resource = retrieve
  resource = Resource.new(self.class, title, :parameters => resource) if resource.is_a? Hash
  resource
end

#self_refresh?Boolean

TODO:

check that meaningful yardoc is produced - this method delegates to “self.class.self_refresh”

Returns:

  • (Boolean)

    true if the type should send itself a refresh event on change.

  • (Boolean)
    • ??? returns true when … what?


2631
2632
2633
# File 'lib/puppet/type.rb', line 2631

def self_refresh?
  self.class.self_refresh
end

#set_default(attr) ⇒ void

TODO:

comment says “For any parameters or properties that have defaults and have not yet been set, set them now. This method can be handed a list of attributes, and if so it will only set defaults for those attributes.”

TODO:

Needs a better explanation, and investigation about the claim an array can be passed (it is passed to self.class.attrclass to produce a class on which a check is made if it has a method class :default (does not seem to support an array…

This method returns an undefined value.


857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
# File 'lib/puppet/type.rb', line 857

def set_default(attr)
  klass = self.class.attrclass(attr)
  return unless klass
  # TODO this is not a necessary check, as we define a class level attr_reader
  return unless klass.method_defined?(:default)
  return if @parameters.include?(klass.name)

  parameter = newattr(klass.name)
  return unless parameter

  value = parameter.default
  if value and ! value.nil?
    parameter.value = value
  else
    @parameters.delete(parameter.name)
  end
end

#should(name) ⇒ Object?

Returns the 'should' (wanted state) value for a specified property, or nil if the given attribute name is not a property (i.e. if it is a parameter, meta-parameter, or does not exist).

Returns:

  • (Object, nil)

    Returns the 'should' (wanted state) value for a specified property, or nil if the given attribute name is not a property (i.e. if it is a parameter, meta-parameter, or does not exist).


761
762
763
764
765
766
767
768
# File 'lib/puppet/type.rb', line 761

def should(name)
  prop = @parameters[name.intern]
  if prop && prop.is_a?(Puppet::Property)
    prop.should
  else
    nil
  end
end

#suitable?Boolean

Returns true if this is something else than a `:provider`, or if it is a provider and it is suitable, or if there is a default provider. Otherwise, false is returned.

Returns:

  • (Boolean)

    Returns true if this is something else than a `:provider`, or if it is a provider and it is suitable, or if there is a default provider. Otherwise, false is returned.


2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
# File 'lib/puppet/type.rb', line 2034

def suitable?
  # If we don't use providers, then we consider it suitable.
  return true unless self.class.paramclass(:provider)

  # We have a provider and it is suitable.
  return true if provider && provider.class.suitable?

  # We're using the default provider and there is one.
  if !provider and self.class.defaultprovider
    self.provider = self.class.defaultprovider.name
    return true
  end

  # We specified an unsuitable provider, or there isn't any suitable
  # provider.
  false
end

#tags=(list) ⇒ void

This method returns an undefined value.

Sets the initial list of tags to associate to this resource.


2255
2256
2257
2258
# File 'lib/puppet/type.rb', line 2255

def tags=(list)
  tag(self.class.name)
  tag(*list)
end

#to_hashHash{ ??? => ??? }

TODO:

the comment says: “Convert our object to a hash. This just includes properties.”

TODO:

this is confused, again it is the @parameters instance variable that is consulted, and each value is copied - does it contain “properties” and “parameters” or both? Does it contain meta-parameters?

Returns a hash of WHAT?. The hash is a shallow copy, any changes to the objects returned in this hash will be reflected in the original resource having these attributes.

Returns:

  • (Hash{ ??? => ??? })

    a hash of WHAT?. The hash is a shallow copy, any changes to the objects returned in this hash will be reflected in the original resource having these attributes.


883
884
885
886
887
888
889
890
891
# File 'lib/puppet/type.rb', line 883

def to_hash
  rethash = {}

  @parameters.each do |name, obj|
    rethash[name] = obj.value
  end

  rethash
end

#to_resourcePuppet::Resource

Convert this resource type instance to a Puppet::Resource.

Returns:


2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
# File 'lib/puppet/type.rb', line 2689

def to_resource
  resource = self.retrieve_resource
  resource.merge_tags_from(self)

  @parameters.each do |name, param|
    # Avoid adding each instance name twice
    next if param.class.isnamevar? and param.value == self.title

    # We've already got property values
    next if param.is_a?(Puppet::Property)
    resource[name] = param.value
  end

  resource
end

#to_sObject

Produces a reference to this in reference format.

See Also:


2682
2683
2684
# File 'lib/puppet/type.rb', line 2682

def to_s
  self.ref
end

#typeString

TODO:

Would that be “file” for the “File” resource type? of “File” or something else?

Returns the name of this object's class.

Returns:

  • (String)

    the name of this object's class


896
897
898
# File 'lib/puppet/type.rb', line 896

def type
  self.class.name
end

#uniqueness_keyObject

Produces a resource's uniqueness_key (or composite key). This key is an array of all key attributes' values. Each distinct tuple must be unique for each resource type.

Returns:

  • (Object)

    an object that is a uniqueness_key for this object

See Also:


453
454
455
# File 'lib/puppet/type.rb', line 453

def uniqueness_key
  self.class.key_attributes.sort_by { |attribute_name| attribute_name.to_s }.map{ |attribute_name| self[attribute_name] }
end

#value(name) ⇒ Object?

TODO:

Comment says “Return a specific value for an attribute.”, as opposed to what “An unspecific value”???

TODO:

is this the 'is' or the 'should' value?

TODO:

why is the return restricted to things that respond to :value? (Only non structural basic data types supported?

Returns the value of the attribute having the given name, or nil if the given name is not an attribute, or the referenced attribute does not respond to `:value`.

Returns:

  • (Object, nil)

    the value of the attribute having the given name, or nil if the given name is not an attribute, or the referenced attribute does not respond to `:value`.


907
908
909
910
911
912
913
914
915
916
# File 'lib/puppet/type.rb', line 907

def value(name)
  name = name.intern

  obj = @parameters[name]
  if obj && obj.respond_to?(:value)
    obj.value
  else
    nil
  end
end

#version???

TODO:

What is this used for? Needs a better explanation.

Returns the version of the catalog or 0 if there is no catalog.

Returns:

  • (???)

    the version of the catalog or 0 if there is no catalog.


920
921
922
923
# File 'lib/puppet/type.rb', line 920

def version
  return 0 unless catalog
  catalog.version
end

#virtual?Boolean

Returns whether the resource is virtual or not

Returns:

  • (Boolean)

    Returns whether the resource is virtual or not


2706
# File 'lib/puppet/type.rb', line 2706

def virtual?;  !!@virtual;  end