module Puppet

The version method and constant are isolated in puppet/version.rb so that a simple `require ‘puppet/version’` allows a rubygems gemspec or bundler Gemfile to get the Puppet version of the gem install.

The version is programatically settable because we want to allow the Raketasks and such to set the version based on the output of `git describe`

see the bottom of the file for the rest of the inclusions

Manage a router abstraction

This is our main way of managing processes right now.

a service is distinct from a process in that services can only be managed through the interface of an init script which is why they have a search path for initscripts and such

Simple module for logging messages on the client-side

Manage SELinux context of files.

This code actually manages three pieces of data in the context.

[root@delenn files]# ls -dZ / drwxr-xr-x root root system_u:object_r:root_t /

The context of ‘/’ here is ‘system_u:object_r:root_t’. This is three seperate fields:

system_u is the user context object_r is the role context root_t is the type context

All three of these fields are returned in a single string by the output of the stat command, but set individually with the chcon command. This allows the user to specify a subset of the three values while leaving the others alone.

See www.nsa.gov/selinux/ for complete docs on SELinux.

Manage file modes. This state should support different formats for specification (e.g., u+rwx, or -0011), but for now only supports specifying the full mode.

This system manages an extensible set of metadata about plugins which it

collects by searching for files named "plugin_init.rb" in a series of
directories.  Initially, these are simply the $LOAD_PATH.

The contents of each file found is executed in the context of a Puppet::Plugins

object (and thus scoped).  An example file might contain:

@name = "Greet the CA"

@description = %q{
  This plugin causes a friendly greeting to print out on a master
  that is operating as the CA, after it has been set up but before
  it does anything.
}

def after_application_setup(options)
  if options[:application_object].is_a?(Puppet::Application::Master) && Puppet::SSL::CertificateAuthority.ca?
    puts "Hey, this is the CA!"
  end
end

Note that the instance variables are local to this Puppet::Plugin (and so may be used

for maintaining state, etc.) but the plugin system does not provide any thread safety
assurances, so they may not be adequate for some complex use cases.

A common module for converting between constants and file names.

The main Puppet class. Everything is contained here.

@api public

Constants

AS_DURATION

NOTE: For information about the available values for the “:type” property of settings,

see the docs for Settings.define_settings
PUPPETVERSION
REGEX

regular expression suitable for use by a ParsedFile based provider

SEPARATOR_REGEX
STORECONFIGS_ONLY
ScheduleMethods
ScheduleScales

Attributes

features[R]
name[W]

Public Instance Methods

bucket() click to toggle source
# File lib/puppet/type/filebucket.rb, line 90
def bucket
  mkbucket unless defined?(@bucket)
  @bucket
end
change_to_s(current_value, newvalue) click to toggle source
# File lib/puppet/type/maillist.rb, line 13
def change_to_s(current_value, newvalue)
  return "Purged #{resource}" if newvalue == :purged
  super
end
check(value) click to toggle source

We always fail this test, because we’re only supposed to run on refresh.

# File lib/puppet/type/exec.rb, line 362
def check(value)
  # We have to invert the values.
  if value == :true
    false
  else
    true
  end
end
check_all_attributes(refreshing = false) click to toggle source

Verify that we pass all of the checks. The argument determines whether we skip the :refreshonly check, which is necessary because we now check within refresh

# File lib/puppet/type/exec.rb, line 554
def check_all_attributes(refreshing = false)
  self.class.checks.each { |check|
    next if refreshing and check == :refreshonly
    if @parameters.include?(check)
      val = @parameters[check].value
      val = [val] unless val.is_a? Array
      val.each do |value|
        return false unless @parameters[check].check(value)
      end
    end
  }

  true
end
checksum() click to toggle source
# File lib/puppet/type/file/source.rb, line 94
def checksum
  metadata && metadata.checksum
end
checksum_type() click to toggle source
# File lib/puppet/type/file/content.rb, line 75
def checksum_type
  if source = resource.parameter(:source)
    result = source.checksum
  else
    result = resource[:checksum]
  end
  if result =~ /^\{(\w+)\}.+/
    return $1.to_sym
  else
    return result
  end
end
chunk_file_from_disk(source_or_content) { |chunk| ... } click to toggle source
# File lib/puppet/type/file/content.rb, line 201
def chunk_file_from_disk(source_or_content)
  File.open(source_or_content.full_path, "rb") do |src|
    while chunk = src.read(8192)
      yield chunk
    end
  end
end
chunk_file_from_source(source_or_content) { |uncompress| ... } click to toggle source
# File lib/puppet/type/file/content.rb, line 220
def chunk_file_from_source(source_or_content)
  get_from_source(source_or_content) do |response|
    case response.code
    when /^2/;  uncompress(response) { |uncompressor| response.read_body { |chunk| yield uncompressor.uncompress(chunk) } }
    else
      # Raise the http error if we didn't get a 'success' of some kind.
      message = "Error #{response.code} on SERVER: #{(response.body||'').empty? ? response.message : uncompress_body(response)}"
      raise Net::HTTPError.new(message, response)
    end
  end
end
clear() click to toggle source

This only exists for testing.

# File lib/puppet/type/package.rb, line 460
def clear
  if obj = @parameters[:ensure]
    obj.latest = nil
  end
end
content() click to toggle source

Look up (if necessary) and return local content.

# File lib/puppet/type/file/source.rb, line 99
def content
  return @content if @content
  raise Puppet::DevError, "No source for content was stored with the metadata" unless metadata.source

  unless tmp = Puppet::FileServing::Content.indirection.find(metadata.source, :environment => resource.catalog.environment, :links => resource[:links])
    self.fail "Could not find any content at %s" % metadata.source
  end
  @content = tmp.content
end
content_is_really_a_checksum?() click to toggle source
# File lib/puppet/type/file/content.rb, line 197
def content_is_really_a_checksum?
  checksum?(should)
end
copy_source_value(metadata_method) click to toggle source
# File lib/puppet/type/file/source.rb, line 225
def copy_source_value(metadata_method)
  param_name = (metadata_method == :checksum) ? :content : metadata_method
  if resource[param_name].nil? or resource[param_name] == :absent
    value = metadata.send(metadata_method)
    # Force the mode value in file resources to be a string containing octal.
    value = value.to_s(8) if param_name == :mode && value.is_a?(Numeric)
    resource[param_name] = value
  end
end
copy_source_values() click to toggle source

Copy the values from the source to the resource. Yay.

# File lib/puppet/type/file/source.rb, line 110
def copy_source_values
  devfail "Somehow got asked to copy source values without any metadata" unless metadata

  # conditionally copy :checksum
  if metadata.ftype != "directory" && !(metadata.ftype == "link" && metadata.links == :manage)
    copy_source_value(:checksum)
  end

  # Take each of the stats and set them as states on the local file
  # if a value has not already been provided.
  [:owner, :mode, :group].each do |metadata_method|
    next if metadata_method == :owner and !Puppet.features.root?
    next if metadata_method == :group and !Puppet.features.root?

    if Puppet.features.microsoft_windows?
      # Warn on Windows if source permissions are being used and the file resource
      # does not have mode owner and group all set (which would take precedence).
      if [:use, :use_when_creating].include?(resource[:source_permissions]) &&
        (resource[:owner] == nil || resource[:group] == nil || resource[:mode] == nil)

        warning = "Copying %s from the source" <<
                  " file on Windows is deprecated;" <<
                  " use source_permissions => ignore."
        Puppet.deprecation_warning(warning % 'owner/mode/group')
        resource.debug(warning % metadata_method.to_s)
      end
      # But never try to copy remote owner/group on Windows
      next if [:owner, :group].include?(metadata_method) && !local?
    end

    case resource[:source_permissions]
    when :ignore
      next
    when :use_when_creating
      next if Puppet::FileSystem.exist?(resource[:path])
    end

    copy_source_value(metadata_method)
  end

  if resource[:ensure] == :absent
    # We know all we need to
  elsif metadata.ftype != "link"
    resource[:ensure] = metadata.ftype
  elsif resource[:links] == :follow
    resource[:ensure] = :present
  else
    resource[:ensure] = "link"
    resource[:target] = metadata.destination
  end
end
current_username() click to toggle source
# File lib/puppet/type/exec.rb, line 588
def current_username
  Etc.getpwuid(Process.uid).name
end
delimiter() click to toggle source
# File lib/puppet/type/host.rb, line 37
def delimiter
  " "
end
desired_mode_from_current(desired, current) click to toggle source
# File lib/puppet/type/file/mode.rb, line 87
def desired_mode_from_current(desired, current)
  current = current.to_i(8) if current.is_a? String
  is_a_directory = @resource.stat && @resource.stat.directory?
  symbolic_mode_to_int(desired, current, is_a_directory)
end
dirmask(value) click to toggle source

If we’re a directory, we need to be executable for all cases that are readable. This should probably be selectable, but eh.

# File lib/puppet/type/file/mode.rb, line 95
def dirmask(value)
  if FileTest.directory?(resource[:path]) and value =~ /^\d+$/ then
    value = value.to_i(8)
    value |= 0100 if value & 0400 != 0
    value |= 010 if value & 040 != 0
    value |= 01 if value & 04 != 0
    value = value.to_s(8)
  end

  value
end
each_chunk_from(source_or_content) { |source_or_content| ... } click to toggle source

the content is munged so if it’s a checksum source_or_content is nil unless the checksum indirectly comes from source

# File lib/puppet/type/file/content.rb, line 179
def each_chunk_from(source_or_content)
  if source_or_content.is_a?(String)
    yield source_or_content
  elsif content_is_really_a_checksum? && source_or_content.nil?
    yield read_file_from_filebucket
  elsif source_or_content.nil?
    yield ''
  elsif Puppet[:default_file_terminus] == :file_server
    yield source_or_content.content
  elsif source_or_content.local?
    chunk_file_from_disk(source_or_content) { |chunk| yield chunk }
  else
    chunk_file_from_source(source_or_content) { |chunk| yield chunk }
  end
end
event_name() click to toggle source
# File lib/puppet/type/exec.rb, line 73
def event_name
  :executed_command
end
exists?() click to toggle source

This method has been exposed for puppet to manage users and groups of files in its settings and should not be considered available outside of puppet.

(see Puppet::Settings#service_group_available?)

@return [Boolean] if the group exists on the system @api private

# File lib/puppet/type/group.rb, line 196
def exists?
  provider.exists?
end
find_unmanaged_keys() click to toggle source

Generate ssh_authorized_keys resources for purging. The key files are taken from the purge_ssh_keys parameter. The generated resources inherit all metaparameters from the parent user resource.

@return [Array<Puppet::Type::Ssh_authorized_key] a list of resources

representing the found keys

@see generate @api private

# File lib/puppet/type/user.rb, line 652
def find_unmanaged_keys
  self[:purge_ssh_keys].
    select { |f| File.readable?(f) }.
    map { |f| unknown_keys_in_file(f) }.
    flatten.each do |res|
      res[:ensure] = :absent
      res[:user] = self[:name]
      @parameters.each do |name, param|
        res[name] = param.value if param.metaparam?
      end
    end
end
found?() click to toggle source
# File lib/puppet/type/file/source.rb, line 221
def found?
  ! (metadata.nil? or metadata.ftype.nil?)
end
full_path() click to toggle source
# File lib/puppet/type/file/source.rb, line 195
def full_path
  Puppet::Util.uri_to_path(uri) if found?
end
generate() click to toggle source
# File lib/puppet/type/maillist.rb, line 48
def generate
  if provider.respond_to?(:aliases)
    should = self.should(:ensure) || :present
    if should == :purged
      should = :absent
    end
    atype = Puppet::Type.type(:mailalias)

    provider.aliases.
      reject  { |name,recipient| catalog.resource(:mailalias, name) }.
      collect { |name,recipient| atype.new(:name => name, :recipient => recipient, :ensure => should) }
  end
end
get_from_source(source_or_content, &block) click to toggle source
# File lib/puppet/type/file/content.rb, line 209
def get_from_source(source_or_content, &block)
  source = source_or_content.metadata.source
  request = Puppet::Indirector::Request.new(:file_content, :find, source, nil, :environment => resource.catalog.environment)

  request.do_request(:fileserver) do |req|
    connection = Puppet::Network::HttpPool.http_instance(req.server, req.port)
    connection.request_get(Puppet::Network::HTTP::API::V1.indirection2uri(req), add_accept_encoding({"Accept" => "raw"}), &block)
  end
end
inclusive?() click to toggle source
# File lib/puppet/type/host.rb, line 41
def inclusive?
  true
end
insync?(is) click to toggle source

insync: mounted -> present

unmounted -> present
# File lib/puppet/type/mount.rb, line 97
def insync?(is)
  if should == :defined and [:mounted,:unmounted].include?(is)
    true
  else
    super
  end
end
is_to_s(currentvalue) click to toggle source
# File lib/puppet/type/group.rb, line 101
def is_to_s(currentvalue)
  if provider.respond_to?(:members_to_s)
    currentvalue = '' if currentvalue.nil?
    currentvalue = currentvalue.is_a?(Array) ? currentvalue : currentvalue.split(',')

    return provider.members_to_s(currentvalue)
  end

  super(currentvalue)
end
Also aliased as: should_to_s
length() click to toggle source
# File lib/puppet/type/file/content.rb, line 88
def length
  (actual_content and actual_content.length) || 0
end
local?() click to toggle source
# File lib/puppet/type/file/source.rb, line 191
def local?
  found? and scheme == "file"
end
match?(previous, now) click to toggle source
# File lib/puppet/type/schedule.rb, line 130
def match?(previous, now)
  # The lowest-level array is of the hour, minute, second triad
  # then it's an array of two of those, to present the limits
  # then it's an array of those ranges
  @value = [@value] unless @value[0][0].is_a?(Array)

  @value.each do |value|
    limits = value.collect do |range|
      ary = [now.year, now.month, now.day, range[0]]
      if range[1]
        ary << range[1]
      else
        ary << 0
      end

      if range[2]
        ary << range[2]
      else
        ary << 0
      end

      time = Time.local(*ary)

      unless time.hour == range[0]
        self.devfail(
          "Incorrectly converted time: #{time}: #{time.hour} vs #{range[0]}"
        )
      end

      time
    end

    unless limits[0] < limits[1]
      self.info(
      "Assuming upper limit should be that time the next day"
      )

      # Find midnight between the two days. Adding one second
      # to the end of the day is easier than dealing with dates.
      ary = limits[0].to_a
      ary[0] = 59
      ary[1] = 59
      ary[2] = 23
      midnight = Time.local(*ary)+1

      # If it is currently between the range start and midnight
      # we consider that a successful match.
      if now.between?(limits[0], midnight)
        # We have to check the weekday match here as it is special-cased
        # to support day-spanning ranges.
        if @resource[:weekday]
          return false unless @resource[:weekday].has_key?(now.wday)
        end
        return true
      end

      # If we didn't match between the starting time and midnight
      # we must now move our midnight back 24 hours and try
      # between the new midnight (24 hours prior) and the
      # ending time.
      midnight -= 86400

      # Now we compare the current time between midnight and the
      # end time.
      if now.between?(midnight, limits[1])
        # This case is the reason weekday matching is special cased
        # in the range parameter. If we match a range that has spanned
        # past midnight we want to match against the weekday when the range
        # started, not when it currently is.
        if @resource[:weekday]
          return false unless @resource[:weekday].has_key?((now - 86400).wday)
        end
        return true
      end

      # If neither of the above matched then we don't match the
      # range schedule.
      return false
    end

    # Check to see if a weekday parameter was specified and, if so,
    # do we match it or not. If we fail we can stop here.
    # This is required because spanning ranges forces us to check
    # weekday within the range parameter.
    if @resource[:weekday]
      return false unless @resource[:weekday].has_key?(now.wday)
    end

    return true if now.between?(*limits)
  end

  # Else, return false, since our current time isn't between
  # any valid times
  false
end
membership() click to toggle source
# File lib/puppet/type/group.rb, line 151
def membership
  :attribute_membership
end
metadata() click to toggle source

Provide, and retrieve if necessary, the metadata for this file. Fail if we can’t find data about this host, and fail if there are any problems in our query.

# File lib/puppet/type/file/source.rb, line 167
def metadata
  return @metadata if @metadata
  return nil unless value
  value.each do |source|
    begin
      options = {
        :environment          => resource.catalog.environment_instance,
        :links                => resource[:links],
        :source_permissions   => resource[:source_permissions]
      }

      if data = Puppet::FileServing::Metadata.indirection.find(source, options)
        @metadata = data
        @metadata.source = source
        break
      end
    rescue => detail
      self.fail Puppet::Error, "Could not retrieve file metadata for #{source}: #{detail}", detail
    end
  end
  self.fail "Could not retrieve information from environment #{resource.catalog.environment} source(s) #{value.join(", ")}" unless @metadata
  @metadata
end
mkbucket() click to toggle source
# File lib/puppet/type/filebucket.rb, line 97
def mkbucket
  # Default is a local filebucket, if no server is given.
  # If the default path has been removed, too, then
  # the puppetmaster is used as default server

  type = "local"
  args = {}
  if self[:path]
    args[:Path] = self[:path]
  else
    args[:Server] = self[:server]
    args[:Port] = self[:port]
  end

  begin
    @bucket = Puppet::FileBucket::Dipper.new(args)
  rescue => detail
    message = "Could not create #{type} filebucket: #{detail}"
    self.log_exception(detail, message)
    self.fail(message)
  end

  @bucket.name = self.name
end
munge(value) click to toggle source
# File lib/puppet/type/mount.rb, line 200
def munge(value)
  munged = super
  if munged
    :yes
  else
    :no
  end
end
output() click to toggle source
# File lib/puppet/type/exec.rb, line 569
def output
  if self.property(:returns).nil?
    return nil
  else
    return self.property(:returns).output
  end
end
port() click to toggle source
# File lib/puppet/type/file/source.rb, line 207
def port
  (uri and uri.port) or Puppet.settings[:masterport]
end
present?(current_values) click to toggle source
# File lib/puppet/type/package.rb, line 472
def present?(current_values)
  super && current_values[:ensure] != :purged
end
property_matches?(current, desired) click to toggle source
# File lib/puppet/type/file/mode.rb, line 118
def property_matches?(current, desired)
  return false unless current
  current_bits = normalize_symbolic_mode(current)
  desired_bits = desired_mode_from_current(desired, current).to_s(8)
  current_bits == desired_bits
end
read_file_from_filebucket() click to toggle source
# File lib/puppet/type/file/content.rb, line 232
def read_file_from_filebucket
  raise "Could not get filebucket from file" unless dipper = resource.bucket
  sum = should.sub(/\{\w+\}/, '')

  dipper.getfile(sum)
rescue => detail
  self.fail Puppet::Error, "Could not retrieve content for #{should} from filebucket: #{detail}", detail
end
refresh() click to toggle source
# File lib/puppet/type/mount.rb, line 275
def refresh
  # Only remount if we're supposed to be mounted.
  provider.remount if self.should(:fstype) != "swap" and provider.mounted?
end
retrieve() click to toggle source
# File lib/puppet/type/service.rb, line 63
def retrieve
  provider.enabled?
end
scheme() click to toggle source
# File lib/puppet/type/file/source.rb, line 217
def scheme
  (uri and uri.scheme)
end
server() click to toggle source
# File lib/puppet/type/file/source.rb, line 203
def server
  (uri and uri.host) or Puppet.settings[:server]
end
server?() click to toggle source
# File lib/puppet/type/file/source.rb, line 199
def server?
   uri and uri.host
end
should() click to toggle source

We actually want to return the whole array here, not just the first value.

# File lib/puppet/type/sshkey.rb, line 36
def should
  defined?(@should) ? @should : nil
end
should=(value) click to toggle source

Make sure we’re also managing the checksum property.

# File lib/puppet/type/file/content.rb, line 135
def should=(value)
  # treat the value as a bytestring, in Ruby versions that support it, regardless of the encoding
  # in which it has been supplied
  value = value.dup.force_encoding(Encoding::ASCII_8BIT) if value.respond_to?(:force_encoding)
  @resource.newattr(:checksum) unless @resource.parameter(:checksum)
  super
end
should_to_s(currentvalue) click to toggle source
Alias for: is_to_s
sync() click to toggle source
# File lib/puppet/type/service.rb, line 93
def sync
  event = super()

  if property = @resource.property(:enable)
    val = property.retrieve
    property.sync unless property.safe_insync?(val)
  end

  event
end
syncothers() click to toggle source
# File lib/puppet/type/mount.rb, line 105
def syncothers
  # We have to flush any changes to disk.
  currentvalues = @resource.retrieve_resource

  # Determine if there are any out-of-sync properties.
  oos = @resource.send(:properties).find_all do |prop|
    unless currentvalues.include?(prop)
      raise Puppet::DevError, "Parent has property %s but it doesn't appear in the current values", [prop.name]
    end
    if prop.name == :ensure
      false
    else
      ! prop.safe_insync?(currentvalues[prop])
    end
  end.each { |prop| prop.sync }.length
  @resource.flush if oos > 0
end
unknown_keys_in_file(keyfile) click to toggle source

Parse an ssh authorized keys file superficially, extract the comments on the keys. These are considered names of possible ssh_authorized_keys resources. Keys that are managed by the present catalog are ignored.

@see generate @api private @return [Array<Puppet::Type::Ssh_authorized_key] a list of resources

representing the found keys
# File lib/puppet/type/user.rb, line 673
def unknown_keys_in_file(keyfile)
  names = []
  name_index = 0
  File.new(keyfile).each do |line|
    next unless line =~ Puppet::Type.type(:ssh_authorized_key).keyline_regex
    # the name is stored in the 4th capture of the regex
    name = $4
    if name.empty?
      key = $3.delete("\n")
      # If no comment is specified for this key, generate a unique internal
      # name. This uses the same rules as
      # provider/ssh_authorized_key/parsed (PUP-3357)
      name = "#{keyfile}:unnamed-#{name_index += 1}"
    end
    names << name
    Puppet.debug "#{self.ref} parsed for purging Ssh_authorized_key[#{name}]"
  end

  names.map { |keyname|
    Puppet::Type.type(:ssh_authorized_key).new(
      :name => keyname,
      :target => keyfile)
  }.reject { |res|
    catalog.resource_refs.include? res.ref
  }
end
uri() click to toggle source
# File lib/puppet/type/file/source.rb, line 211
def uri
  @uri ||= URI.parse(URI.escape(metadata.source))
end
valid_v4?(addr) click to toggle source
# File lib/puppet/type/host.rb, line 11
def valid_v4?(addr)
  if /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ =~ addr
    return $~.captures.all? {|i| i = i.to_i; i >= 0 and i <= 255 }
  end
  return false
end
valid_v6?(addr) click to toggle source
# File lib/puppet/type/host.rb, line 18
def valid_v6?(addr)
  # http://forums.dartware.com/viewtopic.php?t=452
  # ...and, yes, it is this hard.  Doing it programatically is harder.
  return true if addr =~ /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/

  return false
end
value(name) click to toggle source
# File lib/puppet/type/mount.rb, line 280
def value(name)
  name = name.intern
  if property = @parameters[name]
    return property.value
  end
end
value=(*values) click to toggle source

Support both arrays and colon-separated fields.

# File lib/puppet/type/exec.rb, line 187
def value=(*values)
  @value = values.flatten.collect { |val|
    val.split(File::PATH_SEPARATOR)
  }.flatten
end
write(file) click to toggle source
# File lib/puppet/type/file/content.rb, line 168
def write(file)
  resource.parameter(:checksum).sum_stream { |sum|
    each_chunk_from(actual_content || resource.parameter(:source)) { |chunk|
      sum << chunk
      file.print chunk
    }
  }
end
write_temporarily() { |path| ... } click to toggle source
# File lib/puppet/type/file/content.rb, line 155
def write_temporarily
  tempfile = Tempfile.new("puppet-file")
  tempfile.open

  write(tempfile)

  tempfile.close

  yield tempfile.path

  tempfile.delete
end

Public Class Methods

[](param) click to toggle source

Get the value for a setting

@param [Symbol] param the setting to retrieve

@api public

# File lib/puppet.rb, line 56
def self.[](param)
  if param == :debug
    return Puppet::Util::Log.level == :debug
  else
    return @@settings[param]
  end
end
[]=(param,value) click to toggle source

setting access and stuff

# File lib/puppet.rb, line 83
def self.[]=(param,value)
  @@settings[param] = value
  # Ensure that all environment caches are cleared if we're changing the parser
  lookup(:environments).clear_all if param == :parser
end
base_context(settings) click to toggle source

The bindings used for initialization of puppet @api private

# File lib/puppet.rb, line 182
def self.base_context(settings)
  environments = settings[:environmentpath]
  modulepath = Puppet::Node::Environment.split_path(settings[:basemodulepath])

  if environments.empty?
    loaders = [Puppet::Environments::Legacy.new]
  else
    loaders = Puppet::Environments::Directories.from_path(environments, modulepath)
    # in case the configured environment (used for the default sometimes)
    # doesn't exist
    default_environment = Puppet[:environment].to_sym
    if default_environment == :production
      loaders << Puppet::Environments::StaticPrivate.new(
        Puppet::Node::Environment.create(Puppet[:environment].to_sym,
                                         [],
                                         Puppet::Node::Environment::NO_MANIFEST))
    end
  end

  {
    :environments => Puppet::Environments::Cached.new(Puppet::Environments::Combined.new(*loaders)),
    :http_pool => proc {
      require 'puppet/network/http'
      Puppet::Network::HTTP::NoCachePool.new
    }
  }
end
bootstrap_context() click to toggle source

A simple set of bindings that is just enough to limp along to initialization where the {::base_context} bindings are put in place @api private

# File lib/puppet.rb, line 213
def self.bootstrap_context
  root_environment = Puppet::Node::Environment.create(:'*root*', [], Puppet::Node::Environment::NO_MANIFEST)
  {
    :current_environment => root_environment,
    :root_environment => root_environment
  }
end
checks() click to toggle source
# File lib/puppet/type/exec.rb, line 63
def self.checks
  @checks.keys
end
clear() click to toggle source
# File lib/puppet.rb, line 89
def self.clear
  @@settings.clear
end
debug=(value) click to toggle source
# File lib/puppet.rb, line 93
def self.debug=(value)
  if value
    Puppet::Util::Log.level=(:debug)
  else
    Puppet::Util::Log.level=(:notice)
  end
end
default_diffargs() click to toggle source
# File lib/puppet/defaults.rb, line 3
def self.default_diffargs
  if (Facter.value(:kernel) == "AIX" && Facter.value(:kernelmajversion) == "5300")
    ""
  else
    "-u"
  end
end
define_settings(section, hash) click to toggle source

Store a new default value.

# File lib/puppet.rb, line 78
def self.define_settings(section, hash)
  @@settings.define_settings(section, hash)
end
future_parser?(in_environment = nil) click to toggle source

Is the future parser in effect for the given environment, or in :current_environment if no environment is given.

# File lib/puppet.rb, line 269
def self.future_parser?(in_environment = nil)
  env = in_environment || Puppet.lookup(:current_environment) { return Puppet[:parser] == 'future' }
  env.future_parser?
end
genmanifest() click to toggle source
# File lib/puppet.rb, line 118
def self.genmanifest
  if Puppet[:genmanifest]
    puts Puppet.settings.to_manifest
    exit(0)
  end
end
initialize_settings(args = []) click to toggle source

Initialize puppet’s settings. This is intended only for use by external tools that are not

built off of the Faces API or the Puppet::Util::Application class. It may also be used
to initialize state so that a Face may be used programatically, rather than as a stand-alone
command-line tool.

@api public @param args [Array<String>] the command line arguments to use for initialization @return [void]

# File lib/puppet.rb, line 140
def self.initialize_settings(args = [])
  do_initialize_settings_for_run_mode(:user, args)
end
initialize_settings_for_run_mode(run_mode) click to toggle source

Initialize puppet’s settings for a specified run_mode.

@deprecated Use {::initialize_settings}

# File lib/puppet.rb, line 147
def self.initialize_settings_for_run_mode(run_mode)
  Puppet.deprecation_warning("initialize_settings_for_run_mode may be removed in a future release, as may run_mode itself")
  do_initialize_settings_for_run_mode(run_mode, [])
end
instances() click to toggle source
# File lib/puppet/type/schedule.rb, line 416
def self.instances
  []
end
keyline_regex() click to toggle source
# File lib/puppet/type/ssh_authorized_key.rb, line 149
def self.keyline_regex
  REGEX
end
lookup(name, &block) click to toggle source

Lookup a binding by name or return a default value provided by a passed block (if given). @api private

# File lib/puppet.rb, line 237
def self.lookup(name, &block)
  @context.lookup(name, &block)
end
mark_context(name) click to toggle source

@api private

# File lib/puppet.rb, line 252
def self.mark_context(name)
  @context.mark(name)
end
mkdefaultbucket() click to toggle source

Create a default filebucket.

# File lib/puppet/type/filebucket.rb, line 86
def self.mkdefaultbucket
  new(:name => "puppet", :path => Puppet[:clientbucketdir])
end
mkdefaultschedules() click to toggle source
# File lib/puppet/type/schedule.rb, line 420
def self.mkdefaultschedules
  result = []
  unless Puppet[:default_schedules]
    Puppet.debug "Not creating default schedules: default_schedules is false"
    return result
  end

  Puppet.debug "Creating default schedules"

        result << self.new(

    :name => "puppet",
    :period => :hourly,

    :repeat => "2"
  )

  # And then one for every period
  @parameters.find { |p| p.name == :period }.value_collection.values.each { |value|

          result << self.new(
      :name => value.to_s,
      :period => value
    )
  }

  result
end
newcheck(name, options = {}, &block) click to toggle source

Create a new check mechanism. It’s basically just a parameter that provides one extra ‘check’ method.

# File lib/puppet/type/exec.rb, line 56
def self.newcheck(name, options = {}, &block)
  @checks ||= {}

  check = newparam(name, options, &block)
  @checks[name] = check
end
newtype(name, options = {}, &block) click to toggle source

Create a new type. Just proxy to the Type class. The mirroring query code was deprecated in 2008, but this is still in heavy use. I suppose this can count as a soft deprecation for the next dev. –daniel 2011-04-12

# File lib/puppet.rb, line 167
def self.newtype(name, options = {}, &block)
  Puppet::Type.newtype(name, options, &block)
end
override(bindings, description = "", &block) click to toggle source

@param bindings [Hash] A hash of bindings to be merged with the parent context. @param description [String] A description of the context. @yield [] A block executed in the context of the temporarily pushed bindings. @api private

# File lib/puppet.rb, line 245
def self.override(bindings, description = "", &block)
  @context.override(bindings, description, &block)
ensure
  lookup(:root_environment).instance_variable_set(:@future_parser, nil)
end
parse_config() click to toggle source

Parse the config file for this process. @deprecated Use {::initialize_settings}

# File lib/puppet.rb, line 127
def self.parse_config()
  Puppet.deprecation_warning("Puppet.parse_config is deprecated; please use Faces API (which will handle settings and state management for you), or (less desirable) call Puppet.initialize_settings")
  Puppet.initialize_settings
end
pop_context() click to toggle source

Return to the previous context. @raise [StackUnderflow] if the current context is the root @api private

# File lib/puppet.rb, line 231
def self.pop_context
  @context.pop
end
push_context(overrides, description = "") click to toggle source

@param overrides [Hash] A hash of bindings to be merged with the parent context. @param description [String] A description of the context. @api private

# File lib/puppet.rb, line 224
def self.push_context(overrides, description = "")
  @context.push(overrides, description)
end
rollback_context(name) click to toggle source

@api private

# File lib/puppet.rb, line 257
def self.rollback_context(name)
  @context.rollback(name)
end
run_mode() click to toggle source
# File lib/puppet.rb, line 101
def self.run_mode
  # This sucks (the existence of this method); there are a lot of places in our code that branch based the value of
  # "run mode", but there used to be some really confusing code paths that made it almost impossible to determine
  # when during the lifecycle of a puppet application run the value would be set properly.  A lot of the lifecycle
  # stuff has been cleaned up now, but it still seems frightening that we rely so heavily on this value.
  #
  # I'd like to see about getting rid of the concept of "run_mode" entirely, but there are just too many places in
  # the code that call this method at the moment... so I've settled for isolating it inside of the Settings class
  # (rather than using a global variable, as we did previously...).  Would be good to revisit this at some point.
  #
  # --cprice 2012-03-16
  Puppet::Util::RunMode[@@settings.preferred_run_mode]
end
settings() click to toggle source

Note: It’s important that these accessors (`self.settings`, `self.[]`) are defined before we try to load any “features” (which happens a few lines below), because the implementation of the features loading may examine the values of settings.

# File lib/puppet.rb, line 47
def self.settings
  @@settings
end
version() click to toggle source

version is a public API method intended to always provide a fast and lightweight way to determine the version of Puppet.

The intent is that software external to Puppet be able to determine the Puppet version with no side-effects. The expected use is:

require 'puppet/version'
version = Puppet.version

This function has the following ordering precedence. This precedence list is designed to facilitate automated packaging tasks by simply writing to the VERSION file in the same directory as this source file.

1. If a version has been explicitly assigned using the Puppet.version=
   method, return that version.
2. If there is a VERSION file, read the contents, trim any
   trailing whitespace, and return that version string.
3. Return the value of the Puppet::PUPPETVERSION constant hard-coded into
   the source code.

If there is no VERSION file, the method must return the version string of the nearest parent version that is an officially released version. That is to say, if a branch named 3.1.x contains 25 patches on top of the most recent official release of 3.1.1, then the version method must return the string “3.1.1” if no “VERSION” file is present.

By design the version identifier is not intended to vary during the life a process. There is no guarantee provided that writing to the VERSION file while a Puppet process is running will cause the version string to be updated. On the contrary, the contents of the VERSION are cached to reduce filesystem accesses.

The VERSION file is intended to be used by package maintainers who may be applying patches or otherwise changing the software version in a manner that warrants a different software version identifier. The VERSION file is intended to be managed and owned by the release process and packaging related tasks, and as such should not reside in version control. The PUPPETVERSION constant is intended to be version controlled in history.

Ideally, this behavior will allow package maintainers to precisely specify the version of the software they’re packaging as in the following example:

$ git describe --match "3.0.*" > lib/puppet/VERSION
$ ruby -r puppet -e 'puts Puppet.version'
3.0.1-260-g9ca4e54

@api public

@return [String] containing the puppet version, e.g. “3.0.1”

# File lib/puppet/version.rb, line 62
def self.version
  version_file = File.join(File.dirname(__FILE__), 'VERSION')
  return @puppet_version if @puppet_version
  if version = read_version_file(version_file)
    @puppet_version = version
  end
  @puppet_version ||= PUPPETVERSION
end
version=(version) click to toggle source
# File lib/puppet/version.rb, line 71
def self.version=(version)
  @puppet_version = version
end