Class: Puppet::Settings

Inherits:
Object show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/puppet/settings.rb,
lib/puppet/settings/errors.rb

Overview

The class for handling configuration files.

Defined Under Namespace

Classes: AliasSetting, ArraySetting, AutosignSetting, BaseSetting, BooleanSetting, CertificateRevocationSetting, ChainedValues, ConfigFile, DirectorySetting, DurationSetting, EnumSetting, EnvironmentConf, FileOrDirectorySetting, FileSetting, HttpExtraHeadersSetting, IniFile, IntegerSetting, InterpolationError, ParseError, PathSetting, PortSetting, PrioritySetting, SearchPathElement, ServerListSetting, SettingsError, StringSetting, SymbolicEnumSetting, TTLSetting, TerminusSetting, ValidationError, ValueTranslator, Values, ValuesFromEnvironmentConf, ValuesFromSection

Constant Summary collapse

PuppetOptionParser =

local reference for convenience

Puppet::Util::CommandLine::PuppetOptionParser
REQUIRED_APP_SETTINGS =

These are the settings that every app is required to specify; there are reasonable defaults defined in application.rb.

[:logdir, :confdir, :vardir, :codedir]
ALLOWED_SECTION_NAMES =

The acceptable sections of the puppet.conf configuration file.

%w[main server master agent user].freeze
NONE =
'none'
SETTING_TYPES =
{
  :string => StringSetting,
  :file => FileSetting,
  :directory => DirectorySetting,
  :file_or_directory => FileOrDirectorySetting,
  :path => PathSetting,
  :boolean => BooleanSetting,
  :integer => IntegerSetting,
  :port => PortSetting,
  :terminus => TerminusSetting,
  :duration => DurationSetting,
  :ttl => TTLSetting,
  :array => ArraySetting,
  :enum => EnumSetting,
  :symbolic_enum => SymbolicEnumSetting,
  :priority => PrioritySetting,
  :autosign => AutosignSetting,
  :server_list => ServerListSetting,
  :http_extra_headers => HttpExtraHeadersSetting,
  :certificate_revocation => CertificateRevocationSetting,
  :alias => AliasSetting
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSettings

Create a new collection of config settings.



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/puppet/settings.rb', line 137

def initialize
  @config = {}
  @shortnames = {}

  @created = []

  # Keep track of set values.
  @value_sets = {
    :cli => Values.new(:cli, @config),
    :memory => Values.new(:memory, @config),
    :application_defaults => Values.new(:application_defaults, @config),
    :overridden_defaults => Values.new(:overridden_defaults, @config),
  }
  @configuration_file = nil

  # And keep a per-environment cache
  # We can't use Concurrent::Map because we want to preserve insertion order
  @cache_lock = Puppet::Concurrent::Lock.new
  @cache = Concurrent::Hash.new do |hash, key|
    @cache_lock.synchronize do
      break hash[key] if hash.key?(key)

      hash[key] = Concurrent::Hash.new
    end
  end
  @values_lock = Puppet::Concurrent::Lock.new
  @values = Concurrent::Hash.new do |hash, key|
    @values_lock.synchronize do
      break hash[key] if hash.key?(key)

      hash[key] = Concurrent::Hash.new
    end
  end

  # The list of sections we've used.
  @used = []

  @hooks_to_call_on_application_initialization = []
  @deprecated_setting_names = []
  @deprecated_settings_that_have_been_configured = []

  @translate = Puppet::Settings::ValueTranslator.new
  @config_file_parser = Puppet::Settings::ConfigFile.new(@translate)
end

Instance Attribute Details

#timerObject (readonly)

Returns the value of attribute timer.



46
47
48
# File 'lib/puppet/settings.rb', line 46

def timer
  @timer
end

Class Method Details

.app_defaults_for_run_mode(run_mode) ⇒ Object

This method is intended for puppet internal use only; it is a convenience method that returns reasonable application default settings values for a given run_mode.



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/puppet/settings.rb', line 59

def self.app_defaults_for_run_mode(run_mode)
  {
    :name => run_mode.to_s,
    :run_mode => run_mode.name,
    :confdir => run_mode.conf_dir,
    :codedir => run_mode.code_dir,
    :vardir => run_mode.var_dir,
    :publicdir => run_mode.public_dir,
    :rundir => run_mode.run_dir,
    :logdir => run_mode.log_dir,
  }
end

.clean_opt(opt, val) ⇒ Object

A utility method (public, is used by application.rb and perhaps elsewhere) that munges a command-line option string into the format that Puppet.settings expects. (This mostly has to deal with handling the “no-” prefix on flag/boolean options).

Parameters:

  • opt (String)

    the command line option that we are munging

  • val (String, TrueClass, FalseClass)

    the value for the setting (as determined by the OptionParser)



378
379
380
381
382
383
384
385
386
# File 'lib/puppet/settings.rb', line 378

def self.clean_opt(opt, val)
  # rewrite --[no-]option to --no-option if that's what was given
  if opt =~ /\[no-\]/ and !val
    opt = opt.gsub(/\[no-\]/, 'no-')
  end
  # otherwise remove the [no-] prefix to not confuse everybody
  opt = opt.gsub(/\[no-\]/, '')
  [opt, val]
end

.default_certnameObject



72
73
74
75
76
77
78
79
80
81
# File 'lib/puppet/settings.rb', line 72

def self.default_certname
  hostname = hostname_fact
  domain = domain_fact
  if domain and domain != ""
    fqdn = [hostname, domain].join(".")
  else
    fqdn = hostname
  end
  fqdn.to_s.gsub(/\.$/, '')
end

.default_config_file_nameObject



91
92
93
# File 'lib/puppet/settings.rb', line 91

def self.default_config_file_name
  "puppet.conf"
end

.domain_factObject



87
88
89
# File 'lib/puppet/settings.rb', line 87

def self.domain_fact
  Puppet.runtime[:facter].value('networking.domain')
end

.hostname_factObject



83
84
85
# File 'lib/puppet/settings.rb', line 83

def self.hostname_fact
  Puppet.runtime[:facter].value('networking.hostname')
end

Instance Method Details

#[](param) ⇒ 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.

Retrieve a config value

Parameters:

  • param (Symbol)

    the name of the setting

Returns:

  • (Object)

    the value of the setting



186
187
188
189
190
191
# File 'lib/puppet/settings.rb', line 186

def [](param)
  if @deprecated_setting_names.include?(param)
    issue_deprecation_warning(setting(param), "Accessing '#{param}' as a setting is deprecated.")
  end
  value(param)
end

#[]=(param, value) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Set a config value. This doesn’t set the defaults, it sets the value itself.

Parameters:

  • param (Symbol)

    the name of the setting

  • value (Object)

    the new value of the setting



197
198
199
200
201
202
203
# File 'lib/puppet/settings.rb', line 197

def []=(param, value)
  if @deprecated_setting_names.include?(param)
    issue_deprecation_warning(setting(param), "Modifying '#{param}' as a setting is deprecated.")
  end
  @value_sets[:memory].set(param, value)
  unsafe_flush_cache
end

#addargs(options) ⇒ Object

Generate the list of valid arguments, in a format that GetoptLong can understand, and add them to the passed option list.



221
222
223
224
225
226
227
228
# File 'lib/puppet/settings.rb', line 221

def addargs(options)
  # Add all of the settings as valid options.
  each { |_name, setting|
    setting.getopt_args.each { |args| options << args }
  }

  options
end

#app_defaults_initialized?Boolean

Returns:

  • (Boolean)


388
389
390
# File 'lib/puppet/settings.rb', line 388

def app_defaults_initialized?
  @app_defaults_initialized
end

#apply_metadata_from_section(section) ⇒ Object



728
729
730
731
732
733
734
735
# File 'lib/puppet/settings.rb', line 728

def (section)
  section.settings.each do |setting|
    type = @config[setting.name] if setting.has_metadata?
    if type
      type.set_meta(setting.meta)
    end
  end
end

#boolean?(param) ⇒ Boolean

Is our setting a boolean setting?

Returns:

  • (Boolean)


242
243
244
245
# File 'lib/puppet/settings.rb', line 242

def boolean?(param)
  param = param.to_sym
  @config.include?(param) and @config[param].is_a?(BooleanSetting)
end

#clearObject

Remove all set values, potentially skipping cli values.



248
249
250
# File 'lib/puppet/settings.rb', line 248

def clear
  unsafe_clear
end

#clear_environment_settings(environment) ⇒ 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.

Clears all cached settings for a particular environment to ensure that changes to environment.conf are reflected in the settings if the environment timeout has expired.

param [String, Symbol] environment the name of environment to clear settings for



284
285
286
287
288
289
290
291
# File 'lib/puppet/settings.rb', line 284

def clear_environment_settings(environment)
  if environment.nil?
    return
  end

  @cache[environment.to_sym].clear
  @values[environment.to_sym] = {}
end

#clearusedObject



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

def clearused
  @cache.clear
  @used = []
end

#configsearchpath(environment = nil, run_mode = preferred_run_mode) ⇒ Array<SearchPathElement>

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 order in which to search for values, without defaults.

Parameters:

  • environment (String, Symbol) (defaults to: nil)

    symbolic reference to an environment name

  • run_mode (Symbol) (defaults to: preferred_run_mode)

    symbolic reference to a Puppet run mode

Returns:



852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
# File 'lib/puppet/settings.rb', line 852

def configsearchpath(environment = nil, run_mode = preferred_run_mode)
  searchpath = [
    SearchPathElement.new(:memory, :values),
    SearchPathElement.new(:cli, :values)
  ]
  searchpath << SearchPathElement.new(environment.intern, :environment) if environment

  if run_mode
    if [:master, :server].include?(run_mode)
      searchpath << SearchPathElement.new(:server, :section)
      searchpath << SearchPathElement.new(:master, :section)
    else
      searchpath << SearchPathElement.new(run_mode, :section)
    end
  end

  searchpath << SearchPathElement.new(:main, :section)
end

#define_settings(section, defs) ⇒ Object

Define a group of settings.

Parameters:

  • section (Symbol)

    a symbol to use for grouping multiple settings together into a conceptual unit. This value (and the conceptual separation) is not used very often; the main place where it will have a potential impact is when code calls Settings#use method. See docs on that method for further details, but basically that method just attempts to do any preparation that may be necessary before code attempts to leverage the value of a particular setting. This has the most impact for file/directory settings, where #use will attempt to “ensure” those files / directories.

  • defs (Hash[Hash])

    the settings to be defined. This argument is a hash of hashes; each key should be a symbol, which is basically the name of the setting that you are defining. The value should be another hash that specifies the parameters for the particular setting. Legal values include:

    [:default] => not required; this is the value for the setting if no other value is specified (via cli, config file, etc.)
       For string settings this may include "variables", demarcated with $ or ${} which will be interpolated with values of other settings.
       The default value may also be a Proc that will be called only once to evaluate the default when the setting's value is retrieved.
    [:desc] => required; a description of the setting, used in documentation / help generation
    [:type] => not required, but highly encouraged!  This specifies the data type that the setting represents.  If
       you do not specify it, it will default to "string".  Legal values include:
       :string - A generic string setting
       :boolean - A boolean setting; values are expected to be "true" or "false"
       :file - A (single) file path; puppet may attempt to create this file depending on how the settings are used.  This type
           also supports additional options such as "mode", "owner", "group"
       :directory - A (single) directory path; puppet may attempt to create this file depending on how the settings are used.  This type
           also supports additional options such as "mode", "owner", "group"
       :path - This is intended to be used for settings whose value can contain multiple directory paths, represented
           as strings separated by the system path separator (e.g. system path, module path, etc.).
     [:mode] => an (optional) octal value to be used as the permissions/mode for :file and :directory settings
     [:owner] => optional owner username/uid for :file and :directory settings
     [:group] => optional group name/gid for :file and :directory settings
    


1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# File 'lib/puppet/settings.rb', line 1021

def define_settings(section, defs)
  section = section.to_sym
  call = []
  defs.each do |name, hash|
    raise ArgumentError, _("setting definition for '%{name}' is not a hash!") % { name: name } unless hash.is_a? Hash

    name = name.to_sym
    hash[:name] = name
    hash[:section] = section
    raise ArgumentError, _("Setting %{name} is already defined") % { name: name } if @config.include?(name)

    tryconfig = newsetting(hash)
    short = tryconfig.short
    if short
      other = @shortnames[short]
      if other
        raise ArgumentError, _("Setting %{name} is already using short name '%{short}'") % { name: other.name, short: short }
      end

      @shortnames[short] = tryconfig
    end
    @config[name] = tryconfig

    # Collect the settings that need to have their hooks called immediately.
    # We have to collect them so that we can be sure we're fully initialized before
    # the hook is called.
    if tryconfig.has_hook?
      if tryconfig.call_hook_on_define?
        call << tryconfig
      elsif tryconfig.call_hook_on_initialize?
        @hooks_to_call_on_application_initialization |= [tryconfig]
      end
    end

    @deprecated_setting_names << name if tryconfig.deprecated?
  end

  call.each do |setting|
    setting.handle(value(setting.name))
  end
end

#description(name) ⇒ Object

Return a value’s description.



442
443
444
445
446
447
448
449
# File 'lib/puppet/settings.rb', line 442

def description(name)
  obj = @config[name.to_sym]
  if obj
    obj.desc
  else
    nil
  end
end

#eachsectionObject

Iterate over each section name.



454
455
456
457
458
459
460
461
462
463
# File 'lib/puppet/settings.rb', line 454

def eachsection
  yielded = []
  @config.each_value do |object|
    section = object.section
    unless yielded.include? section
      yield section
      yielded << section
    end
  end
end

#flush_cacheObject

Clear @cache, @used and the Environment.

Whenever an object is returned by Settings, a copy is stored in @cache. As long as Setting attributes that determine the content of returned objects remain unchanged, Settings can keep returning objects from @cache without re-fetching or re-generating them.

Whenever a Settings attribute changes, such as @values or @preferred_run_mode, this method must be called to clear out the caches so that updated objects will be returned.



303
304
305
# File 'lib/puppet/settings.rb', line 303

def flush_cache
  unsafe_flush_cache
end

#generate_configObject



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

def generate_config
  puts to_config
  true
end

#generate_manifestObject



559
560
561
562
# File 'lib/puppet/settings.rb', line 559

def generate_manifest
  puts to_manifest
  true
end

#global_defaults_initialized?Boolean

Returns:

  • (Boolean)


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

def global_defaults_initialized?
  @global_defaults_initialized
end

#handlearg(opt, value = nil) ⇒ Object

Handle a command-line argument.



474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
# File 'lib/puppet/settings.rb', line 474

def handlearg(opt, value = nil)
  @cache.clear

  case value
  when FalseClass
    value = "false"
  when TrueClass
    value = "true"
  end

  value &&= @translate[value]
  str = opt.sub(/^--/, '')

  bool = true
  newstr = str.sub(/^no-/, '')
  if newstr != str
    str = newstr
    bool = false
  end
  str = str.intern

  if @config[str].is_a?(Puppet::Settings::BooleanSetting)
    if value == "" or value.nil?
      value = bool
    end
  end

  s = @config[str]
  if s
    @deprecated_settings_that_have_been_configured << s if s.completely_deprecated?
  end

  @value_sets[:cli].set(str, value)
  unsafe_flush_cache
end

#include?(name) ⇒ Boolean

Returns:

  • (Boolean)


510
511
512
513
# File 'lib/puppet/settings.rb', line 510

def include?(name)
  name = name.intern if name.is_a? String
  @config.include?(name)
end

#initialize_app_defaults(app_defaults) ⇒ Object



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/puppet/settings.rb', line 392

def initialize_app_defaults(app_defaults)
  REQUIRED_APP_SETTINGS.each do |key|
    raise SettingsError, "missing required app default setting '#{key}'" unless app_defaults.has_key?(key)
  end

  app_defaults.each do |key, value|
    if key == :run_mode
      self.preferred_run_mode = value
    else
      @value_sets[:application_defaults].set(key, value)
      unsafe_flush_cache
    end
  end
  
  call_hooks_deferred_to_application_initialization
  issue_deprecations

  REQUIRED_APP_SETTINGS.each do |key|
    create_ancestors(Puppet[key])
  end

  @app_defaults_initialized = true
end

#initialize_global_settings(args = [], require_config = true) ⇒ Object

Raises:



321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/puppet/settings.rb', line 321

def initialize_global_settings(args = [], require_config = true)
  raise Puppet::DevError, _("Attempting to initialize global default settings more than once!") if global_defaults_initialized?

  # The first two phases of the lifecycle of a puppet application are:
  # 1) Parse the command line options and handle any of them that are
  #    registered, defined "global" puppet settings (mostly from defaults.rb).
  # 2) Parse the puppet config file(s).

  parse_global_options(args)
  parse_config_files(require_config)

  @global_defaults_initialized = true
end

#optparse_addargs(options) ⇒ Object

Generate the list of valid arguments, in a format that OptionParser can understand, and add them to the passed option list.



232
233
234
235
236
237
238
239
# File 'lib/puppet/settings.rb', line 232

def optparse_addargs(options)
  # Add all of the settings as valid options.
  each { |_name, setting|
    options << setting.optparse_args
  }

  options
end

#override_default(param, value) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Create a new default value for the given setting. The default overrides are higher precedence than the defaults given in defaults.rb, but lower precedence than any other values for the setting. This allows one setting ‘a` to change the default of setting `b`, but still allow a user to provide a value for setting `b`.

Parameters:

  • param (Symbol)

    the name of the setting

  • value (Object)

    the new default value for the setting



214
215
216
217
# File 'lib/puppet/settings.rb', line 214

def override_default(param, value)
  @value_sets[:overridden_defaults].set(param, value)
  unsafe_flush_cache
end

#parse_config(text, file = "text") ⇒ Object



596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
# File 'lib/puppet/settings.rb', line 596

def parse_config(text, file = "text")
  begin
    data = @config_file_parser.parse_file(file, text, ALLOWED_SECTION_NAMES)
  rescue => detail
    Puppet.log_exception(detail, "Could not parse #{file}: #{detail}")
    return
  end

  # If we get here and don't have any data, we just return and don't muck with the current state of the world.
  return if data.nil?

  # If we get here then we have some data, so we need to clear out any
  # previous settings that may have come from config files.
  unsafe_clear(false, false)

  # Screen settings which have been deprecated and removed from puppet.conf
  # but are still valid on the command line and/or in environment.conf
  screen_non_puppet_conf_settings(data)

  # Make note of deprecated settings we will warn about later in initialization
  record_deprecations_from_puppet_conf(data)

  # And now we can repopulate with the values from our last parsing of the config files.
  @configuration_file = data

  # Determine our environment, if we have one.
  if @config[:environment]
    env = value(:environment).to_sym
  else
    env = NONE
  end

  # Call any hooks we should be calling.
  value_sets = value_sets_for(env, preferred_run_mode)
  @config.values.select(&:has_hook?).each do |setting|
    value_sets.each do |source|
      next unless source.include?(setting.name)

      # We still have to use value to retrieve the value, since
      # we want the fully interpolated value, not $vardir/lib or whatever.
      # This results in extra work, but so few of the settings
      # will have associated hooks that it ends up being less work this
      # way overall.
      if setting.call_hook_on_initialize?
        @hooks_to_call_on_application_initialization |= [setting]
      else
        setting.handle(ChainedValues.new(
          preferred_run_mode,
          env,
          value_sets,
          @config
        ).interpolate(setting.name))
      end
      break
    end
  end

  call_hooks_deferred_to_application_initialization :ignore_interpolation_dependency_errors => true
  
end

#parse_file(file, allowed_sections = []) ⇒ Puppet::Settings::ConfigFile::Conf

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method just turns a file into a new ConfigFile::Conf instance

Parameters:

  • file (String)

    absolute path to the configuration file

Returns:



1260
1261
1262
# File 'lib/puppet/settings.rb', line 1260

def parse_file(file, allowed_sections = [])
  @config_file_parser.parse_file(file, read_file(file), allowed_sections)
end

#patch_value(param, value, type) ⇒ 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.

Patches the value for a param in a section. This method is required to support the use case of unifying –dns-alt-names and –dns_alt_names in the certificate face. Ideally this should be cleaned up. See PUP-3684 for more information. For regular use of setting a value, the method ‘[]=` should be used.



985
986
987
988
989
990
# File 'lib/puppet/settings.rb', line 985

def patch_value(param, value, type)
  if @value_sets[type]
    @value_sets[type].set(param, value)
    unsafe_flush_cache
  end
end

#persection(section) ⇒ Object

Iterate across all of the objects in a given section.



791
792
793
794
795
796
797
798
# File 'lib/puppet/settings.rb', line 791

def persection(section)
  section = section.to_sym
  each { |_name, obj|
    if obj.section == section
      yield obj
    end
  }
end

#preferred_run_modeObject

The currently configured run mode that is preferred for constructing the application configuration.



576
577
578
# File 'lib/puppet/settings.rb', line 576

def preferred_run_mode
  @preferred_run_mode_name || :user
end

#preferred_run_mode=(mode) ⇒ 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.

PRIVATE! This only exists because we need a hook to validate the run mode when it’s being set, and

it should never, ever, ever, ever be called from outside of this file.

This method is also called when –run_mode MODE is used on the command line to set the default

Parameters:

  • mode (String|Symbol)

    the name of the mode to have in effect

Raises:



586
587
588
589
590
591
592
593
594
# File 'lib/puppet/settings.rb', line 586

def preferred_run_mode=(mode)
  mode = mode.to_s.downcase.intern
  raise ValidationError, "Invalid run mode '#{mode}'" unless [:server, :master, :agent, :user].include?(mode)

  @preferred_run_mode_name = mode
  # Changing the run mode has far-reaching consequences. Flush any cached
  # settings so they will be re-generated.
  flush_cache
end

Prints the contents of a config file with the available config settings, or it prints a single value of a config setting.



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
# File 'lib/puppet/settings.rb', line 517

def print_config_options
  if Puppet::Util::Log.sendlevel?(:info)
    Puppet::Util::Log.newdestination(:console)
    message = _("Using --configprint is deprecated. Use 'puppet config <subcommand>' instead.")
    Puppet.deprecation_warning(message)
  end

  env = value(:environment)
  val = value(:configprint)
  if val == "all"
    hash = {}
    each do |name, _obj|
      val = value(name, env)
      val = val.inspect if val == ""
      hash[name] = val
    end
    hash.sort { |a, b| a[0].to_s <=> b[0].to_s }.each do |name, v|
      puts "#{name} = #{v}"
    end
  else
    val.split(/\s*,\s*/).sort.each do |v|
      if include?(v)
        # if there is only one value, just print it for back compatibility
        if v == val
          puts value(val, env)
          break
        end
        puts "#{v} = #{value(v, env)}"
      else
        puts "invalid setting: #{v}"
        return false
      end
    end
  end
  true
end


564
565
566
567
568
569
# File 'lib/puppet/settings.rb', line 564

def print_configs
  return print_config_options if value(:configprint) != ""
  return generate_config if value(:genconfig)

  generate_manifest if value(:genmanifest)
end

Returns:

  • (Boolean)


571
572
573
# File 'lib/puppet/settings.rb', line 571

def print_configs?
  (value(:configprint) != "" || value(:genconfig) || value(:genmanifest)) && true
end

#reparse_config_filesObject

Reparse our config file, if necessary.



801
802
803
804
805
806
807
808
809
810
# File 'lib/puppet/settings.rb', line 801

def reparse_config_files
  if files
    filename = any_files_changed?
    if filename
      Puppet.notice "Config file #{filename} changed; triggering re-parse of all config files."
      parse_config_files
      reuse
    end
  end
end

#reuseObject



836
837
838
839
840
841
842
# File 'lib/puppet/settings.rb', line 836

def reuse
  return unless defined?(@used)

  new = @used
  @used = []
  use(*new)
end

#searchpath(environment = nil, run_mode = preferred_run_mode) ⇒ Array<SearchPathElement>

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 order in which to search for values.

Parameters:

  • environment (String, Symbol) (defaults to: nil)

    symbolic reference to an environment name

  • run_mode (Symbol) (defaults to: preferred_run_mode)

    symbolic reference to a Puppet run mode

Returns:



877
878
879
880
881
# File 'lib/puppet/settings.rb', line 877

def searchpath(environment = nil, run_mode = preferred_run_mode)
  searchpath = configsearchpath(environment, run_mode)
  searchpath << SearchPathElement.new(:application_defaults, :values)
  searchpath << SearchPathElement.new(:overridden_defaults, :values)
end

#searchpath_values(source) ⇒ 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.

Get values from a search path entry.



932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
# File 'lib/puppet/settings.rb', line 932

def searchpath_values(source)
  case source.type
  when :values
    @value_sets[source.name]
  when :section
    section = @configuration_file.sections[source.name] if @configuration_file
    if section
      ValuesFromSection.new(source.name, section)
    end
  when :environment
    ValuesFromEnvironmentConf.new(source.name)
  else
    raise Puppet::DevError, _("Unknown searchpath case: %{source_type} for the %{source} settings path element.") % { source_type: source.type, source: source }
  end
end

#service_group_available?Boolean

Returns:

  • (Boolean)


899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
# File 'lib/puppet/settings.rb', line 899

def service_group_available?
  return @service_group_available if defined?(@service_group_available)

  if self[:group]
    group = Puppet::Type.type(:group).new :name => self[:group], :audit => :ensure

    if group.suitable?
      @service_group_available = group.exists?
    else
      raise Puppet::Error, (_("Cannot manage group permissions, because the provider for '%{name}' is not functional") % { name: group })
    end
  else
    @service_group_available = false
  end
end

#service_user_available?Boolean

Returns:

  • (Boolean)


883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
# File 'lib/puppet/settings.rb', line 883

def service_user_available?
  return @service_user_available if defined?(@service_user_available)

  if self[:user]
    user = Puppet::Type.type(:user).new :name => self[:user], :audit => :ensure

    if user.suitable?
      @service_user_available = user.exists?
    else
      raise Puppet::Error, (_("Cannot manage owner permissions, because the provider for '%{name}' is not functional") % { name: user })
    end
  else
    @service_user_available = false
  end
end

#set_by_cli(param) ⇒ Object?

Allow later inspection to determine if the setting was set on the command line, or through some other code path. Used for the ‘dns_alt_names` option during cert generate. –daniel 2011-10-18

Parameters:

  • param (String, Symbol)

    the setting to look up

Returns:

  • (Object, nil)

    the value of the setting or nil if unset



921
922
923
924
# File 'lib/puppet/settings.rb', line 921

def set_by_cli(param)
  param = param.to_sym
  @value_sets[:cli].lookup(param)
end

#set_by_cli?(param) ⇒ Boolean

Returns:

  • (Boolean)


926
927
928
# File 'lib/puppet/settings.rb', line 926

def set_by_cli?(param)
  !!set_by_cli(param)
end

#set_by_config?(param, environment = nil, run_mode = preferred_run_mode) ⇒ Boolean

Allow later inspection to determine if the setting was set by user config, rather than a default setting.

Returns:

  • (Boolean)


950
951
952
953
954
955
956
957
958
# File 'lib/puppet/settings.rb', line 950

def set_by_config?(param, environment = nil, run_mode = preferred_run_mode)
  param = param.to_sym
  configsearchpath(environment, run_mode).any? do |source|
    vals = searchpath_values(source)
    if vals
      vals.lookup(param)
    end
  end
end

#set_in_section(param, section) ⇒ Object?

Allow later inspection to determine if the setting was set in a specific section

Parameters:

  • param (String, Symbol)

    the setting to look up

  • section (Symbol)

    the section in which to look up the setting

Returns:

  • (Object, nil)

    the value of the setting or nil if unset



966
967
968
969
970
971
972
# File 'lib/puppet/settings.rb', line 966

def set_in_section(param, section)
  param = param.to_sym
  vals = searchpath_values(SearchPathElement.new(section, :section))
  if vals
    vals.lookup(param)
  end
end

#set_in_section?(param, section) ⇒ Boolean

Returns:

  • (Boolean)


974
975
976
# File 'lib/puppet/settings.rb', line 974

def set_in_section?(param, section)
  !!set_in_section(param, section)
end

#setting(param) ⇒ Puppet::Settings::BaseSetting

Returns a given setting by name

Parameters:

  • name (Symbol)

    The name of the setting to fetch

Returns:



468
469
470
471
# File 'lib/puppet/settings.rb', line 468

def setting(param)
  param = param.to_sym
  @config[param]
end

#stringify_settings(section, settings = :all) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/puppet/settings.rb', line 95

def stringify_settings(section, settings = :all)
  values_from_the_selected_section =
    values(nil, section.to_sym)

  loader_settings = {
    :environmentpath => values_from_the_selected_section.interpolate(:environmentpath),
    :basemodulepath => values_from_the_selected_section.interpolate(:basemodulepath),
  }

  Puppet.override(Puppet.base_context(loader_settings),
                  _("New environment loaders generated from the requested section.")) do
    # And now we can lookup values that include those from environments configured from
    # the requested section
    values = values(Puppet[:environment].to_sym, section.to_sym)

    to_be_rendered = {}
    settings = Puppet.settings.to_a.collect(&:first) if settings == :all
    settings.sort.each do |setting_name|
      to_be_rendered[setting_name] = values.print(setting_name.to_sym)
    end

    stringifyhash(to_be_rendered)
  end
end

#stringifyhash(hash) ⇒ Object



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/puppet/settings.rb', line 120

def stringifyhash(hash)
  newhash = {}
  hash.each do |key, val|
    key = key.to_s
    case val
    when Hash
      newhash[key] = stringifyhash(val)
    when Symbol
      newhash[key] = val.to_s
    else
      newhash[key] = val
    end
  end
  newhash
end

#to_catalog(*sections) ⇒ Object

Convert the settings we manage into a catalog full of resources that model those settings.



1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
# File 'lib/puppet/settings.rb', line 1064

def to_catalog(*sections)
  sections = nil if sections.empty?

  catalog = Puppet::Resource::Catalog.new("Settings", Puppet::Node::Environment::NONE)
  @config.keys.find_all { |key| @config[key].is_a?(FileSetting) }.each do |key|
    file = @config[key]
    next if file.value.nil?
    next unless sections.nil? or sections.include?(file.section)

    resource = file.to_resource
    next unless resource
    next if catalog.resource(resource.ref)

    Puppet.debug { "Using settings: adding file resource '#{key}': '#{resource.inspect}'" }

    catalog.add_resource(resource)
  end

  add_user_resources(catalog, sections)
  add_environment_resources(catalog, sections)

  catalog
end

#to_configObject

Convert our list of config settings into a configuration file.



1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
# File 'lib/puppet/settings.rb', line 1089

def to_config
  str = %(The configuration file for #{Puppet.run_mode.name}.  Note that this file
is likely to have unused settings in it; any setting that's
valid anywhere in Puppet can be in any config file, even if it's not used.

Every section can specify three special parameters: owner, group, and mode.
These parameters affect the required permissions of any files specified after
their specification.  Puppet will sometimes use these parameters to check its
own configured state, so they can be used to make Puppet a bit more self-managing.

The file format supports octothorpe-commented lines, but not partial-line comments.

Generated on #{Time.now}.
).gsub(/^/, "# ")

  #         Add a section heading that matches our name.
  str += "[#{preferred_run_mode}]\n"
  eachsection do |section|
    persection(section) do |obj|
      str += obj.to_config + "\n" unless obj.name == :genconfig
    end
  end

  str
end

#to_manifestObject

Convert to a parseable manifest



1116
1117
1118
1119
1120
1121
# File 'lib/puppet/settings.rb', line 1116

def to_manifest
  catalog = to_catalog
  catalog.resource_refs.collect do |ref|
    catalog.resource(ref).to_manifest
  end.join("\n\n")
end

#use(*sections) ⇒ Object

Create the necessary objects to use a section. This is idempotent; you can ‘use’ a section as many times as you want.



1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
# File 'lib/puppet/settings.rb', line 1125

def use(*sections)
  if Puppet[:settings_catalog]
    sections = sections.collect(&:to_sym)
    sections = sections.reject { |s| @used.include?(s) }

    Puppet.warning(":master section deprecated in favor of :server section") if sections.include?(:master)

    # add :server if sections include :master or :master if sections include :server
    sections |= [:master, :server] if (sections & [:master, :server]).any?

    sections = sections.collect(&:to_sym)
    sections = sections.reject { |s| @used.include?(s) }

    return if sections.empty?

    Puppet.debug { "Applying settings catalog for sections #{sections.join(', ')}" }

    begin
      catalog = to_catalog(*sections).to_ral
    rescue => detail
      Puppet.log_and_raise(detail, "Could not create resources for managing Puppet's files and directories in sections #{sections.inspect}: #{detail}")
    end

    catalog.host_config = false
    catalog.apply do |transaction|
      if transaction.any_failed?
        report = transaction.report
        status_failures = report.resource_statuses.values.select(&:failed?)
        status_fail_msg = status_failures
                          .collect(&:events)
                          .flatten
                          .select { |event| event.status == 'failure' }
                          .collect { |event| "#{event.resource}: #{event.message}" }.join("; ")

        raise "Got #{status_failures.length} failure(s) while initializing: #{status_fail_msg}"
      end
    end

    sections.each { |s| @used << s }
    @used.uniq!
  else
    Puppet.debug("Skipping settings catalog for sections #{sections.join(', ')}")
  end
end

#valid?(param) ⇒ Boolean

Returns:

  • (Boolean)


1170
1171
1172
1173
# File 'lib/puppet/settings.rb', line 1170

def valid?(param)
  param = param.to_sym
  @config.has_key?(param)
end

#value(param, environment = nil, bypass_interpolation = false) ⇒ Object

Find the correct value using our search path.

Parameters:

  • param (String, Symbol)

    The value to look up

  • environment (String, Symbol) (defaults to: nil)

    The environment to check for the value

  • bypass_interpolation (true, false) (defaults to: false)

    Whether to skip interpolation

Returns:

  • (Object)

    The looked up value

Raises:



1200
1201
1202
1203
# File 'lib/puppet/settings.rb', line 1200

def value(param, environment = nil, bypass_interpolation = false)
  environment &&= environment.to_sym
  value_sym(param.to_sym, environment, bypass_interpolation)
end

#value_sym(param, environment = nil, bypass_interpolation = false) ⇒ Object

Find the correct value using symbols and our search path.

Parameters:

  • param (Symbol)

    The value to look up

  • environment (Symbol) (defaults to: nil)

    The environment to check for the value

  • bypass_interpolation (true, false) (defaults to: false)

    Whether to skip interpolation

Returns:

  • (Object)

    The looked up value

Raises:



1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
# File 'lib/puppet/settings.rb', line 1214

def value_sym(param, environment = nil, bypass_interpolation = false)
  # Check the cache first.  It needs to be a per-environment
  # cache so that we don't spread values from one env
  # to another.
  cached_env = @cache[environment || NONE]

  # Avoid two lookups in cache_env unless val is nil. When it is, it's important
  # to check if the key is included so that further processing (that will result
  # in nil again) is avoided.
  val = cached_env[param]
  return val if !val.nil? || cached_env.include?(param)

  # Short circuit to nil for undefined settings.
  return nil unless @config.include?(param)

  vals = values(environment, preferred_run_mode)
  val = bypass_interpolation ? vals.lookup(param) : vals.interpolate(param)
  cached_env[param] = val
  val
end

#values(environment, section) ⇒ Puppet::Settings::ChainedValues

Retrieve an object that can be used for looking up values of configuration settings.

Parameters:

  • environment (Symbol)

    The name of the environment in which to lookup

  • section (Symbol)

    The name of the configuration section in which to lookup

Returns:



1182
1183
1184
1185
1186
1187
1188
1189
# File 'lib/puppet/settings.rb', line 1182

def values(environment, section)
  @values[environment][section] ||= ChainedValues.new(
    section,
    environment,
    value_sets_for(environment, section),
    @config
  )
end

#which_configuration_fileObject

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.

TODO:

this code duplicates Util::RunMode#which_dir as described in #16637

(#15337) All of the logic to determine the configuration file to use

should be centralized into this method.  The simplified approach is:
  1. If there is an explicit configuration file, use that. (–confdir or –config)

  2. If we’re running as a root process, use the system puppet.conf (usually /etc/puppetlabs/puppet/puppet.conf)

  3. Otherwise, use the user puppet.conf (usually ~/.puppetlabs/etc/puppet/puppet.conf)



1248
1249
1250
1251
1252
1253
1254
# File 'lib/puppet/settings.rb', line 1248

def which_configuration_file
  if explicit_config_file? or Puppet.features.root? then
    main_config_file
  else
    user_config_file
  end
end