Class: Puppet::Provider

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

Overview

Note:

An instance of a Provider is associated with one resource.

Note:

Class level methods are only called once to configure the provider (when the type is created), and not for each resource the provider is operating on. The instance methods are however called for each resource.

A Provider is an implementation of the actions that manage resources (of some type) on a system. This class is the base class for all implementation of a Puppet Provider.

Concepts: –

  • Confinement - confinement restricts providers to only be applicable under certain conditions.

    It is possible to confine a provider several different ways:
    * the included {#confine} method which provides filtering on fact, feature, existence of files, or a free form
      predicate.
    * the {commands} method that filters on the availability of given system commands.
    
  • **Property hash** - the important instance variable ‘@property_hash` contains all current state values for properties (it is lazily built). It is important that these values are managed appropriately in the methods Provider.instances, Provider.prefetch, and in methods that alters the current state (those that change the lifecycle (creates, destroys), or alters some value reflected backed by a property).

  • Flush - is a hook that is called once per resource when everything has been applied. The intent is that an implementation may defer modification of the current state typically done in property setters and instead record information that allows flush to perform the changes more efficiently.

  • **Execution Methods** - The execution methods provides access to execution of arbitrary commands. As a convenience execution methods are available on both the instance and the class of a provider since a lot of provider logic switch between these contexts fairly freely.

  • **System Entity/Resource** - this documentation uses the term “system entity” for system resources to make it clear if talking about a resource on the system being managed (e.g. a file in the file system) or about a description of such a resource (e.g. a Puppet Resource).

  • **Resource Type** - this is an instance of Type that describes a classification of instances of Resource (e.g. the ‘File` resource type describes all instances of `file` resources). (The term is used to contrast with “type” in general, and specifically to contrast with the implementation class of Resource or a specific Type).

Defined Under Namespace

Modules: Mount Classes: AixObject, Cisco, Command, CommandDefiner, Exec, Ldap, Naginator, NameService, NetworkDevice, Package, ParsedFile

Constant Summary collapse

Confine =
Puppet::Confine

Constants included from Util::Logging

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

Constants included from Util

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

Constants included from Util::POSIX

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

Constants included from Util::SymbolicFileMode

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

Constants included from Util::Docs

Util::Docs::HEADER_LEVELS

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_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, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, safe_posix_fork, set_env, symbolizehash, thinmark, uri_encode, uri_query_encode, uri_to_path, which, withenv, withumask

Methods included from Util::POSIX

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

Methods included from Util::SymbolicFileMode

#normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Methods included from Util::Docs

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

Methods included from Util::Warnings

clear_warnings, debug_once, notice_once, warnonce

Methods included from Confiner

confine, confine_collection, suitable?

Methods included from Util::Errors

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

Constructor Details

#initialize(resource = nil) ⇒ Provider

TODO:

The use of a hash as a parameter needs a better explanation; why is this done? What is the intent?

Creates a new provider that is optionally initialized from a resource or a hash of properties. If no argument is specified, a new non specific provider is initialized. If a resource is given it is remembered for further operations. If a hash is used it becomes the internal ‘@property_hash` structure of the provider - this hash holds the current state property values of system entities as they are being discovered by querying or other operations (typically getters).

Parameters:



510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/puppet/provider.rb', line 510

def initialize(resource = nil)
  if resource.is_a?(Hash)
    # We don't use a duplicate here, because some providers (ParsedFile, at least)
    # use the hash here for later events.
    @property_hash = resource
  elsif resource
    @resource = resource
    @property_hash = {}
  else
    @property_hash = {}
  end
end

Class Attribute Details

.desc=(value) ⇒ Object (writeonly)

Sets the documentation of this provider class. (The full documentation is read via the doc attribute).



91
# File 'lib/puppet/provider.rb', line 91

attr_writer :doc

.docString

The (full) documentation for this provider class. The documentation for the provider class itself should be set with the DSL method desc=. Setting the documentation with with doc= has the same effect as setting it with desc= (only the class documentation part is set). In essence this means that there is no getter for the class documentation part (since the getter returns the full documentation when there are additional contributors).

Returns:

  • (String)

    Returns the full documentation for the provider.



91
# File 'lib/puppet/provider.rb', line 91

attr_writer :doc

.nameString

Returns The name of the provider.

Returns:

  • (String)

    The name of the provider



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

def name
  @name
end

.resource_typePuppet::Type

TODO:

What is this type? A reference to a Puppet::Type ?

Returns the resource type (that this provider is … WHAT?).

Returns:

  • (Puppet::Type)

    the resource type (that this provider is … WHAT?)



70
71
72
# File 'lib/puppet/provider.rb', line 70

def resource_type
  @resource_type
end

.sourceString

TODO:

Unclear what “the source” is used for?

Returns the data source, which is the provider name if no other source has been set.

Returns:

  • (String)

    Returns the data source, which is the provider name if no other source has been set.



432
433
434
# File 'lib/puppet/provider.rb', line 432

def self.source
  @source ||= self.name
end

Instance Attribute Details

#resource???

Returns This resource is what? Is an instance of a provider attached to one particular Puppet::Resource?.

Returns:

  • (???)

    This resource is what? Is an instance of a provider attached to one particular Puppet::Resource?



96
97
98
# File 'lib/puppet/provider.rb', line 96

def resource
  @resource
end

Class Method Details

.command(name) ⇒ String

Returns the absolute path to the executable for the command referenced by the given name.

Returns:

  • (String)

    the absolute path to the found executable for the command

Raises:

See Also:



138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/puppet/provider.rb', line 138

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

  if defined?(@commands) and command = @commands[name]
    # nothing
  elsif superclass.respond_to? :command and command = superclass.command(name)
    # nothing
  else
    raise Puppet::DevError, "No command #{name} defined for provider #{self.name}"
  end

  which(command)
end

.commands(command_specs) ⇒ void

Note:

It is preferred if the commands are not entered with absolute paths as this allows puppet to search for them using the PATH variable.

This method returns an undefined value.

Confines this provider to be suitable only on hosts where the given commands are present. Also see Confiner#confine for other types of confinement of a provider by use of other types of predicates.

Parameters:

  • command_specs (Hash{String => String})

    Map of name to command that the provider will be executing on the system. Each command is specified with a name and the path of the executable.

See Also:



165
166
167
168
169
# File 'lib/puppet/provider.rb', line 165

def self.commands(command_specs)
  command_specs.each do |name, path|
    has_command(name, path)
  end
end

.declared_feature?(name) ⇒ Boolean

Return whether the given feature has been declared or not.

Returns:

  • (Boolean)

    Return whether the given feature has been declared or not.



264
265
266
# File 'lib/puppet/provider.rb', line 264

def self.declared_feature?(name)
  defined?(@declared_features) and @declared_features.include?(name)
end

.default?Boolean

Returns whether this implementation satisfies all of the default requirements or not. Returns false if there is no matching defaultfor

Returns:

  • (Boolean)

    Returns whether this implementation satisfies all of the default requirements or not. Returns false if there is no matching defaultfor

See Also:



272
273
274
# File 'lib/puppet/provider.rb', line 272

def self.default?
  default_match ? true : false
end

.default_matchHash<{String => 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.

Look through the array of defaultfor hashes and return the first match.

Returns:

  • (Hash<{String => Object}>)

    the matching hash specified by a defaultfor

See Also:



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

def self.default_match
  @defaults.find do |default|
    default.all? do |key, values|
      case key
        when :feature
          feature_match(values)
        else
          fact_match(key, values)
      end
    end
  end
end

.defaultfor(hash) ⇒ void

This method returns an undefined value.

Sets a facts filter that determine which of several suitable providers should be picked by default. This selection only kicks in if there is more than one suitable provider. To filter on multiple facts the given hash may contain more than one fact name/value entry. The filter picks the provider if all the fact/value entries match the current set of facts. (In case there are still more than one provider after this filtering, the first found is picked).

Parameters:

  • hash (Hash<{String => Object}>)

    hash of fact name to fact value.



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

def self.defaultfor(hash)
  @defaults << hash
end

.execfail(*args) ⇒ Puppet::Util::Execution::ProcessOutput

Deprecated.

Wraps execution of execute with mapping of exception to given exception (and output as argument).

Returns:

Raises:

  • (exception)

    under same conditions as execute, but raises the given ‘exception` with the output as argument



129
130
131
# File 'lib/puppet/provider.rb', line 129

def self.execfail(*args)
  Puppet::Util::Execution.execfail(*args)
end

.execpipe(*args) {|pipe| ... } ⇒ String

The command can be a simple string, which is executed as-is, or an Array, which is treated as a set of command arguments to pass through.

In either case, the command is passed directly to the shell, STDOUT and STDERR are connected together, and STDOUT will be streamed to the yielded pipe.

Parameters:

  • command (String, Array<String>)

    the command to execute as one string, or as parts in an array. The parts of the array are joined with one separating space between each entry when converting to the command line string to execute.

  • failonfail (Boolean)

    (true) if the execution should fail with Exception on failure or not.

Yields:

  • (pipe)

    to a block executing a subprocess

Yield Parameters:

  • pipe (IO)

    the opened pipe

Yield Returns:

  • (String)

    the output to return

Returns:

  • (String)

    a string with the output from the subprocess executed by the given block

Raises:

  • (Puppet::ExecutionFailure)

    if the executed child process did not exit with status == 0 and ‘failonfail` is `true`.

See Also:

  • for `mode` values


116
117
118
# File 'lib/puppet/provider.rb', line 116

def self.execpipe(*args, &block)
  Puppet::Util::Execution.execpipe(*args, &block)
end

.execute(*args) ⇒ Puppet::Util::Execution::ProcessOutput

Note:

Unfortunately, the default behavior for failonfail and combine (since 0.22.4 and 0.24.7, respectively) depend on whether options are specified or not. If specified, then failonfail and combine default to false (even when the options specified are neither failonfail nor combine). If no options are specified, then failonfail and combine default to true.

Executes the desired command, and return the status and output. def execute(command, options)

Parameters:

  • command (Array<String>, String)

    the command to execute. If it is an Array the first element should be the executable and the rest of the elements should be the individual arguments to that executable.

  • options (Hash)

    a Hash of options

Returns:

Raises:

  • (Puppet::ExecutionFailure)

    if the executed chiled process did not exit with status == 0 and ‘failonfail` is `true`.



105
106
107
# File 'lib/puppet/provider.rb', line 105

def self.execute(*args)
  Puppet::Util::Execution.execute(*args)
end

.fact_match(fact, values) ⇒ Object



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

def self.fact_match(fact, values)
  values = [values] unless values.is_a? Array
  values.map! { |v| v.to_s.downcase.intern }

  if fval = Facter.value(fact).to_s and fval != ""
    fval = fval.to_s.downcase.intern

    values.include?(fval)
  else
    false
  end
end

.feature_match(value) ⇒ Object



306
307
308
# File 'lib/puppet/provider.rb', line 306

def self.feature_match(value)
  Puppet.features.send(value.to_s + "?")
end

.has_command(name, path) {|| ... } ⇒ Object

Note:

the name ´has_command´ looks odd in an API context, but makes more sense when seen in the internal DSL context where a Provider is declaratively defined.

Creates a convenience method for invocation of a command.

This generates a Provider method that allows easy execution of the command. The generated method may take arguments that will be passed through to the executable as the command line arguments when it is invoked.

Examples:

Use it like this:

has_command(:echo, "/bin/echo")
def some_method
  echo("arg 1", "arg 2")
end

. . . or like this

has_command(:echo, "/bin/echo") do
  is_optional
  environment :HOME => "/var/tmp", :PWD => "/tmp"
end

Parameters:

  • name (Symbol)

    The name of the command (will become the name of the generated method that executes the command)

  • path (String)

    The path to the executable for the command

Yields:

  • ()

    A block that configures the command (see Command)



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

def self.has_command(name, path, &block)
  name = name.intern
  command = CommandDefiner.define(name, path, self, &block)

  @commands[name] = command.executable

  # Now define the class and instance methods.
  create_class_and_instance_method(name) do |*args|
    return command.execute(*args)
  end
end

.initvarsvoid

This method returns an undefined value.

Initializes defaults and commands (i.e. clears them).



344
345
346
347
# File 'lib/puppet/provider.rb', line 344

def self.initvars
  @defaults = []
  @commands = {}
end

.instancesArray<Puppet::Provider>

This method is abstract.

this method must be implemented by a subclass and this super method should never be called as it raises an exception.

Note:

The returned instances are instance of some subclass of Provider, not resources.

Returns a list of system resources (entities) this provider may/can manage. This is a query mechanism that lists entities that the provider may manage on a given system. It is is directly used in query services, but is also the foundation for other services; prefetching, and purging.

As an example, a package provider lists all installed packages. (In contrast, the File provider does not list all files on the file-system as that would make execution incredibly slow). An implementation of this method should be made if it is possible to quickly (with a single system call) provide all instances.

An implementation of this method should only cache the values of properties if they are discovered as part of the process for finding existing resources. Resource properties that require additional commands (than those used to determine existence/identity) should be implemented in their respective getter method. (This is important from a performance perspective; it may be expensive to compute, as well as wasteful as all discovered resources may perhaps not be managed).

An implementation may return an empty list (naturally with the effect that it is not possible to query for manageable entities).

By implementing this method, it is possible to use the ‘resources´ resource type to specify purging of all non managed entities.

Returns:

  • (Array<Puppet::Provider>)

    a list of providers referencing the system entities

Raises:

  • (Puppet::DevError)

    Error indicating that the method should have been implemented by subclass.

See Also:



376
377
378
# File 'lib/puppet/provider.rb', line 376

def self.instances
  raise Puppet::DevError, "Provider #{self.name} has not defined the 'instances' class method"
end

.mk_resource_methodsvoid

This method returns an undefined value.

Creates getter- and setter- methods for each property supported by the resource type. Call this method to generate simple accessors for all properties supported by the resource type. These simple accessors lookup and sets values in the property hash. The generated methods may be overridden by more advanced implementations if something else than a straight forward getter/setter pair of methods is required. (i.e. define such overriding methods after this method has been called)

An implementor of a provider that makes use of ‘prefetch` and `flush` can use this method since it uses the internal `@property_hash` variable to store values. An implementation would then update the system state on a call to `flush` based on the current values in the `@property_hash`.



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/puppet/provider.rb', line 393

def self.mk_resource_methods
  [resource_type.validproperties, resource_type.parameters].flatten.each do |attr|
    attr = attr.intern
    next if attr == :name
    define_method(attr) do
      if @property_hash[attr].nil?
        :absent
      else
        @property_hash[attr]
      end
    end

    define_method(attr.to_s + "=") do |val|
      @property_hash[attr] = val
    end
  end
end

.optional_commands(hash) ⇒ Object

Defines optional commands. Since Puppet 2.7.8 this is typically not needed as evaluation of provider suitability is lazy (when a resource is evaluated) and the absence of commands that will be present after other resources have been applied no longer needs to be specified as optional. (@see #has_command)

Parameters:

  • hash (Hash{String => String})

    Named commands that the provider will be executing on the system. Each command is specified with a name and the path of the executable.

See Also:



181
182
183
184
185
186
187
# File 'lib/puppet/provider.rb', line 181

def self.optional_commands(hash)
  hash.each do |name, target|
    has_command(name, target) do
      is_optional
    end
  end
end

.post_resource_evalvoid

This method is abstract.

A subclass may implement this - it is not implemented in the Provider class

This method returns an undefined value.

This method may be implemented by a provider in order to perform any cleanup actions needed. It will be called at the end of the transaction if any resources in the catalog make use of the provider, regardless of whether the resources are changed or not and even if resource failures occur.

Since:

  • 3.4.0



# File 'lib/puppet/provider.rb', line 584

.prefetch(resource_hash) ⇒ void

This method is abstract.

A subclass may implement this - it is not implemented in the Provider class

This method returns an undefined value.

This method may be implemented by a provider in order to pre-fetch resource properties. If implemented it should set the provider instance of the managed resources to a provider with the fetched state (i.e. what is returned from the instances method).

Parameters:

  • resources_hash (Hash<{String => Puppet::Resource}>)

    map from name to resource of resources to prefetch



# File 'lib/puppet/provider.rb', line 574

.specificityInteger

Note:

Because of how this value is calculated there could be surprising side effects if a provider included an excessive amount of classes.

The number of requirements is based on the hash size of the matching defaultfor.

The ancestors is the Ruby Module::ancestors method and the number of classes returned is used to boost the score. The intent is that if two providers are equal, but one is more “derived” than the other (i.e. includes more classes), it should win because it is more specific).

Returns:

  • (Integer)

    Returns a numeric specificity for this provider based on how many requirements it has and number of ancestors. The higher the number the more specific the provider.



332
333
334
335
336
337
338
339
340
# File 'lib/puppet/provider.rb', line 332

def self.specificity
  # This strange piece of logic attempts to figure out how many parent providers there
  # are to increase the score. What is will actually do is count all classes that Ruby Module::ancestors
  # returns (which can be other classes than those the parent chain) - in a way, an odd measure of the
  # complexity of a provider).
  match = default_match
  length = match ? match.length : 0
  (length * 100) + ancestors.select { |a| a.is_a? Class }.length
end

.supports_parameter?(param) ⇒ Boolean

Returns true if the given attribute/parameter is supported by the provider. The check is made that the parameter is a valid parameter for the resource type, and then if all its required features (if any) are supported by the provider.

Parameters:

Returns:

  • (Boolean)

    Returns whether this provider supports the given parameter or not.

Raises:

  • (Puppet::DevError)

    if the given parameter is not valid for the resource type



444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/puppet/provider.rb', line 444

def self.supports_parameter?(param)
  if param.is_a?(Class)
    klass = param
  else
    unless klass = resource_type.attrclass(param)
      raise Puppet::DevError, "'#{param}' is not a valid parameter for #{resource_type.name}"
    end
  end
  return true unless features = klass.required_features

  !!satisfies?(*features)
end

Instance Method Details

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

Compares this provider against another provider. Comparison is only possible with another provider (no other class). The ordering is based on the class name of the two providers.

Returns:

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

    A comparison result -1, 0, +1 if this is before other, equal or after other. Returns nil oif not comparable to other.

See Also:

  • Comparable


567
568
569
570
571
572
# File 'lib/puppet/provider.rb', line 567

def <=>(other)
  # We can only have ordering against other providers.
  return nil unless other.is_a? Puppet::Provider
  # Otherwise, order by the providers class name.
  return self.class.name <=> other.class.name
end

#clearObject

Clears this provider instance to allow GC to clean up.



484
485
486
# File 'lib/puppet/provider.rb', line 484

def clear
  @resource = nil
end

#command(name) ⇒ String

Returns the absolute path to the executable for the command referenced by the given name.

Returns:

  • (String)

    the absolute path to the found executable for the command

Raises:

See Also:



489
490
491
# File 'lib/puppet/provider.rb', line 489

def command(name)
  self.class.command(name)
end

#execfail(*args) ⇒ Object

Deprecated.

Convenience methods - see class method with the same name.



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

def execfail(*args)
  Puppet::Util::Execution.execfail(*args)
end

#execpipe(*args, &block) ⇒ Object

Convenience methods - see class method with the same name.



111
112
113
# File 'lib/puppet/provider.rb', line 111

def execpipe(*args, &block)
  Puppet::Util::Execution.execpipe(*args, &block)
end

#execute(*args) ⇒ Object

Convenience methods - see class method with the same name.



100
101
102
# File 'lib/puppet/provider.rb', line 100

def execute(*args)
  Puppet::Util::Execution.execute(*args)
end

#flushvoid

This method is abstract.

A subclass may implement this - it is not implemented in the Provider class

This method returns an undefined value.

This method may be implemented by a provider in order to flush properties that has not been individually applied to the managed entity’s current state.



# File 'lib/puppet/provider.rb', line 595

#get(param) ⇒ Object

Returns the value of a parameter value, or ‘:absent` if it is not defined.

Parameters:

Returns:

  • (Object)

    the value of the parameter or ‘:absent` if not defined.



497
498
499
# File 'lib/puppet/provider.rb', line 497

def get(param)
  @property_hash[param.intern] || :absent
end

#inspectString

Returns a human readable string with information about the resource and the provider.

Returns:

  • (String)

    Returns a human readable string with information about the resource and the provider.



554
555
556
# File 'lib/puppet/provider.rb', line 554

def inspect
  to_s
end

#nameString

Returns the name of the resource this provider is operating on.

Returns:

  • (String)

    the name of the resource instance (e.g. the file path of a File).

Raises:



527
528
529
530
531
532
533
534
535
# File 'lib/puppet/provider.rb', line 527

def name
  if n = @property_hash[:name]
    return n
  elsif self.resource
    resource.name
  else
    raise Puppet::DevError, "No resource and no name in property hash in #{self.class.name} instance"
  end
end

#set(params) ⇒ void

This method returns an undefined value.

Sets the given parameters values as the current values for those parameters. Other parameters are unchanged.

Parameters:

  • params (Array<Puppet::Parameter>)

    the parameters with values that should be set



542
543
544
545
546
# File 'lib/puppet/provider.rb', line 542

def set(params)
  params.each do |param, value|
    @property_hash[param.intern] = value
  end
end

#to_sString

Returns a human readable string with information about the resource and the provider.

Returns:

  • (String)

    Returns a human readable string with information about the resource and the provider.



549
550
551
# File 'lib/puppet/provider.rb', line 549

def to_s
  "#{@resource}(provider=#{self.class.name})"
end