repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_behaviours/path_parameters.rb
spec/shared_behaviours/path_parameters.rb
# In order to use this correctly you must define a method to get an instance # of the type being tested, so that this code can remain generic: # # it_should_behave_like "all path parameters", :path do # def instance(path) # Puppet::Type.type(:example).new( # :name => 'foo', :require => 'bar', :path_param => path # ) # end # # That method will be invoked for each test to create the instance that we # subsequently test through the system; you should ensure that the minimum of # possible attributes are set to keep the tests clean. # # You must also pass the symbolic name of the parameter being tested to the # block, and optionally can pass a hash of additional options to the block. # # The known options are: # :array :: boolean, does this support arrays of paths, default true. shared_examples_for "all pathname parameters with arrays" do |win32| path_types = { "unix absolute" => %q{/foo/bar}, "unix relative" => %q{foo/bar}, "win32 non-drive absolute" => %q{\foo\bar}, "win32 non-drive relative" => %q{foo\bar}, "win32 drive absolute" => %q{c:\foo\bar}, "win32 drive relative" => %q{c:foo\bar} } describe "when given an array of paths" do (1..path_types.length).each do |n| path_types.keys.combination(n) do |set| data = path_types.collect { |k, v| set.member?(k) ? v : nil } .compact has_relative = set.find { |k| k =~ /relative/ or k =~ /non-drive/ } has_windows = set.find { |k| k =~ /win32/ } has_unix = set.find { |k| k =~ /unix/ } if has_relative or (has_windows and !win32) or (has_unix and win32) reject = true else reject = false end it "should #{reject ? 'reject' : 'accept'} #{set.join(", ")}" do if reject then expect { instance(data) }. to raise_error Puppet::Error, /fully qualified/ else instance = instance(data) expect(instance[@param]).to eq(data) end end it "should #{reject ? 'reject' : 'accept'} #{set.join(", ")} doubled" do if reject then expect { instance(data + data) }. to raise_error Puppet::Error, /fully qualified/ else instance = instance(data + data) expect(instance[@param]).to eq(data + data) end end end end end end shared_examples_for "all path parameters" do |param, options| # Extract and process options to the block. options ||= {} array = options[:array].nil? ? true : options.delete(:array) if options.keys.length > 0 then fail "unknown options for 'all path parameters': " + options.keys.sort.join(', ') end def instance(path) fail "we didn't implement the 'instance(path)' method in the it_should_behave_like block" end ######################################################################## # The actual testing code... before :all do @param = param end describe "on a Unix-like platform it", :if => Puppet.features.posix? do if array then it_should_behave_like "all pathname parameters with arrays", false end it "should accept a fully qualified path" do path = File.join('', 'foo') instance = instance(path) expect(instance[@param]).to eq(path) end it "should give a useful error when the path is not absolute" do path = 'foo' expect { instance(path) }. to raise_error Puppet::Error, /fully qualified/ end { "Unix" => '/', "Win32" => '\\' }.each do |style, slash| %w{q Q a A z Z c C}.sort.each do |drive| it "should reject drive letter '#{drive}' with #{style} path separators" do path = "#{drive}:#{slash}Program Files" expect { instance(path) }. to raise_error Puppet::Error, /fully qualified/ end end end end describe "on a Windows-like platform it", :if => Puppet::Util::Platform.windows? do if array then it_should_behave_like "all pathname parameters with arrays", true end it "should reject a fully qualified unix path" do path = '/foo' expect { instance(path) }.to raise_error(Puppet::Error, /fully qualified/) end it "should give a useful error when the path is not absolute" do path = 'foo' expect { instance(path) }. to raise_error Puppet::Error, /fully qualified/ end it "also accepts Unix style path separators" do path = 'C:/Program Files' instance = instance(path) expect(instance[@param]).to eq(path) end { "Unix" => '/', "Win32" => '\\' }.each do |style, slash| %w{q Q a A z Z c C}.sort.each do |drive| it "should accept drive letter '#{drive}' with #{style} path separators " do path = "#{drive}:#{slash}Program Files" instance = instance(path) expect(instance[@param]).to eq(path) end end end { "UNC paths" => %q{\\\\foo\bar}, "unparsed local paths" => %q{\\\\?\c:\foo}, "unparsed UNC paths" => %q{\\\\?\foo\bar} }.each do |name, path| it "should accept #{name} as absolute" do instance = instance(path) expect(instance[@param]).to eq(path) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_behaviours/file_serving.rb
spec/shared_behaviours/file_serving.rb
shared_examples_for "Puppet::FileServing::Files" do |indirection| %w[find search].each do |method| let(:request) { Puppet::Indirector::Request.new(indirection, method, 'foo', nil) } describe "##{method}" do it "should proxy to file terminus if the path is absolute" do request.key = make_absolute('/tmp/foo') expect_any_instance_of(described_class.indirection.terminus(:file).class).to receive(method).with(request) subject.send(method, request) end it "should proxy to file terminus if the protocol is file" do request.protocol = 'file' expect_any_instance_of(described_class.indirection.terminus(:file).class).to receive(method).with(request) subject.send(method, request) end describe "when the protocol is puppet" do before :each do request.protocol = 'puppet' end describe "and a server is specified" do before :each do request.server = 'puppet_server' end it "should proxy to rest terminus if default_file_terminus is rest" do Puppet[:default_file_terminus] = "rest" expect_any_instance_of(described_class.indirection.terminus(:rest).class).to receive(method).with(request) subject.send(method, request) end it "should proxy to rest terminus if default_file_terminus is not rest" do Puppet[:default_file_terminus] = 'file_server' expect_any_instance_of(described_class.indirection.terminus(:rest).class).to receive(method).with(request) subject.send(method, request) end end describe "and no server is specified" do before :each do request.server = nil end it "should proxy to file_server if default_file_terminus is 'file_server'" do Puppet[:default_file_terminus] = 'file_server' expect_any_instance_of(described_class.indirection.terminus(:file_server).class).to receive(method).with(request) subject.send(method, request) end it "should proxy to rest if default_file_terminus is 'rest'" do Puppet[:default_file_terminus] = "rest" expect_any_instance_of(described_class.indirection.terminus(:rest).class).to receive(method).with(request) subject.send(method, request) end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_behaviours/all_parsedfile_providers.rb
spec/shared_behaviours/all_parsedfile_providers.rb
shared_examples_for "all parsedfile providers" do |provider, *files| if files.empty? then files = my_fixtures end files.flatten.each do |file| it "should rewrite #{file} reasonably unchanged" do allow(provider).to receive(:default_target).and_return(file) provider.prefetch text = provider.to_file(provider.target_records(file)) text.gsub!(/^# HEADER.+\n/, '') oldlines = File.readlines(file) newlines = text.chomp.split "\n" oldlines.zip(newlines).each do |old, new| expect(new.gsub(/\s+/, '')).to eq(old.chomp.gsub(/\s+/, '')) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_behaviours/memory_terminus.rb
spec/shared_behaviours/memory_terminus.rb
shared_examples_for "A Memory Terminus" do it "should find no instances by default" do expect(@searcher.find(@request)).to be_nil end it "should be able to find instances that were previously saved" do @searcher.save(@request) expect(@searcher.find(@request)).to equal(@instance) end it "should replace existing saved instances when a new instance with the same name is saved" do @searcher.save(@request) two = double('second', :name => @name) trequest = double('request', :key => @name, :instance => two) @searcher.save(trequest) expect(@searcher.find(@request)).to equal(two) end it "should be able to remove previously saved instances" do @searcher.save(@request) @searcher.destroy(@request) expect(@searcher.find(@request)).to be_nil end it "should fail when asked to destroy an instance that does not exist" do expect { @searcher.destroy(@request) }.to raise_error(ArgumentError) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_behaviours/an_indirector_face.rb
spec/shared_behaviours/an_indirector_face.rb
shared_examples_for "an indirector face" do [:find, :search, :save, :destroy, :info].each do |action| it { is_expected.to be_action action } it { is_expected.to respond_to action } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_behaviours/store_configs_terminus.rb
spec/shared_behaviours/store_configs_terminus.rb
shared_examples_for "a StoreConfigs terminus" do before :each do Puppet[:storeconfigs] = true Puppet[:storeconfigs_backend] = "store_configs_testing" end api = [:find, :search, :save, :destroy, :head] api.each do |name| it { is_expected.to respond_to(name) } end it "should fail if an invalid backend is configured" do Puppet[:storeconfigs_backend] = "synergy" expect { subject }.to raise_error(ArgumentError, /could not find terminus synergy/i) end it "should wrap the declared backend" do expect(subject.target.class.name).to eq(:store_configs_testing) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_behaviours/things_that_declare_options.rb
spec/shared_behaviours/things_that_declare_options.rb
# encoding: UTF-8 shared_examples_for "things that declare options" do it "should support options without arguments" do thing = add_options_to { option "--bar" } expect(thing).to be_option :bar end it "should support options with an empty block" do thing = add_options_to do option "--foo" do # this section deliberately left blank end end expect(thing).to be expect(thing).to be_option :foo end { "--foo=" => :foo }.each do |input, option| it "should accept #{name.inspect}" do thing = add_options_to { option input } expect(thing).to be_option option end end it "should support option documentation" do text = "Sturm und Drang (German pronunciation: [ˈʃtʊʁm ʊnt ˈdʁaŋ]) …" thing = add_options_to do option "--foo" do description text summary text end end expect(thing.get_option(:foo).description).to eq(text) end it "should list all the options" do thing = add_options_to do option "--foo" option "--bar", '-b' option "-q", "--quux" option "-f" option "--baz" end expect(thing.options).to eq([:foo, :bar, :quux, :f, :baz]) end it "should detect conflicts in long options" do expect { add_options_to do option "--foo" option "--foo" end }.to raise_error ArgumentError, /Option foo conflicts with existing option foo/i end it "should detect conflicts in short options" do expect { add_options_to do option "-f" option "-f" end }.to raise_error ArgumentError, /Option f conflicts with existing option f/ end ["-f", "--foo"].each do |option| ["", " FOO", "=FOO", " [FOO]", "=[FOO]"].each do |argument| input = option + argument it "should detect conflicts within a single option like #{input.inspect}" do expect { add_options_to do option input, input end }.to raise_error ArgumentError, /duplicates existing alias/ end end end # Verify the range of interesting conflicts to check for ordering causing # the behaviour to change, or anything exciting like that. [ %w{--foo}, %w{-f}, %w{-f --foo}, %w{--baz -f}, %w{-f --baz}, %w{-b --foo}, %w{--foo -b} ].each do |conflict| base = %w{--foo -f} it "should detect conflicts between #{base.inspect} and #{conflict.inspect}" do expect { add_options_to do option(*base) option(*conflict) end }.to raise_error ArgumentError, /conflicts with existing option/ end end it "should fail if we are not consistent about taking an argument" do expect { add_options_to do option "--foo=bar", "--bar" end }. to raise_error ArgumentError, /inconsistent about taking an argument/ end it "should not accept optional arguments" do expect do thing = add_options_to do option "--foo=[baz]", "--bar=[baz]" end [:foo, :bar].each do |name| expect(thing).to be_option name end end.to raise_error(ArgumentError, /optional arguments are not supported/) end describe "#takes_argument?" do it "should detect an argument being absent" do thing = add_options_to do option "--foo" end expect(thing.get_option(:foo)).not_to be_takes_argument end ["=FOO", " FOO"].each do |input| it "should detect an argument given #{input.inspect}" do thing = add_options_to do option "--foo#{input}" end expect(thing.get_option(:foo)).to be_takes_argument end end end describe "#optional_argument?" do it "should be false if no argument is present" do option = add_options_to do option "--foo" end.get_option(:foo) expect(option).not_to be_takes_argument expect(option).not_to be_optional_argument end ["=FOO", " FOO"].each do |input| it "should be false if the argument is mandatory (like #{input.inspect})" do option = add_options_to do option "--foo#{input}" end.get_option(:foo) expect(option).to be_takes_argument expect(option).not_to be_optional_argument end end ["=[FOO]", " [FOO]"].each do |input| it "should fail if the argument is optional (like #{input.inspect})" do expect do option = add_options_to do option "--foo#{input}" end.get_option(:foo) expect(option).to be_takes_argument expect(option).to be_optional_argument end.to raise_error(ArgumentError, /optional arguments are not supported/) end end end describe "#default_to" do it "should not have a default value by default" do option = add_options_to do option "--foo" end.get_option(:foo) expect(option).not_to be_has_default end it "should accept a block for the default value" do option = add_options_to do option "--foo" do default_to do 12 end end end.get_option(:foo) expect(option).to be_has_default end it "should invoke the block when asked for the default value" do invoked = false option = add_options_to do option "--foo" do default_to do invoked = true end end end.get_option(:foo) expect(option).to be_has_default expect(option.default).to be_truthy expect(invoked).to be_truthy end it "should return the value of the block when asked for the default" do option = add_options_to do option "--foo" do default_to do 12 end end end.get_option(:foo) expect(option).to be_has_default expect(option.default).to eq(12) end it "should invoke the block every time the default is requested" do option = add_options_to do option "--foo" do default_to do {} end end end.get_option(:foo) first = option.default.object_id second = option.default.object_id third = option.default.object_id expect(first).not_to eq(second) expect(first).not_to eq(third) expect(second).not_to eq(third) end it "should fail if the option has a default and is required" do expect { add_options_to do option "--foo" do required default_to do 12 end end end }.to raise_error ArgumentError, /can't be optional and have a default value/ expect { add_options_to do option "--foo" do default_to do 12 end required end end }.to raise_error ArgumentError, /can't be optional and have a default value/ end it "should fail if default_to has no block" do expect { add_options_to do option "--foo" do default_to end end }. to raise_error ArgumentError, /default_to requires a block/ end it "should fail if default_to is invoked twice" do expect { add_options_to do option "--foo" do default_to do 12 end default_to do "fun" end end end }.to raise_error ArgumentError, /already has a default value/ end [ "one", "one, two", "one, *two" ].each do |input| it "should fail if the block has the wrong arity (#{input})" do expect { add_options_to do option "--foo" do eval "default_to do |#{input}| 12 end" end end }.to raise_error ArgumentError, /should not take any arguments/ end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_behaviours/hiera_indirections.rb
spec/shared_behaviours/hiera_indirections.rb
shared_examples_for "Hiera indirection" do |test_klass, fixture_dir| include PuppetSpec::Files def write_hiera_config(config_file, datadir) File.open(config_file, 'w') do |f| f.write("--- :yaml: :datadir: #{datadir} :hierarchy: ['global', 'invalid'] :logger: 'noop' :backends: ['yaml'] ") end end def request(key) Puppet::Indirector::Request.new(:hiera, :find, key, nil) end before do hiera_config_file = tmpfile("hiera.yaml") Puppet.settings[:hiera_config] = hiera_config_file write_hiera_config(hiera_config_file, fixture_dir) end after do test_klass.instance_variable_set(:@hiera, nil) end it "should be the default data_binding terminus" do expect(Puppet.settings[:data_binding_terminus]).to eq(:hiera) end it "should raise an error if we don't have the hiera feature" do expect(Puppet.features).to receive(:hiera?).and_return(false) expect { test_klass.new }.to raise_error RuntimeError, "Hiera terminus not supported without hiera library" end describe "the behavior of the hiera_config method", :if => Puppet.features.hiera? do it "should override the logger and set it to puppet" do expect(test_klass.hiera_config[:logger]).to eq("puppet") end context "when the Hiera configuration file does not exist" do let(:path) { File.expand_path('/doesnotexist') } before do Puppet.settings[:hiera_config] = path end it "should log a warning" do expect(Puppet).to receive(:warning).with( "Config file #{path} not found, using Hiera defaults") test_klass.hiera_config end it "should only configure the logger and set it to puppet" do expect(Puppet).to receive(:warning).with( "Config file #{path} not found, using Hiera defaults") expect(test_klass.hiera_config).to eq({ :logger => 'puppet' }) end end end describe "the behavior of the find method", :if => Puppet.features.hiera? do let(:data_binder) { test_klass.new } it "should support looking up an integer" do expect(data_binder.find(request("integer"))).to eq(3000) end it "should support looking up a string" do expect(data_binder.find(request("string"))).to eq('apache') end it "should support looking up an array" do expect(data_binder.find(request("array"))).to eq([ '0.ntp.puppetlabs.com', '1.ntp.puppetlabs.com', ]) end it "should support looking up a hash" do expect(data_binder.find(request("hash"))).to eq({ 'user' => 'Hightower', 'group' => 'admin', 'mode' => '0644' }) end it "raises a data binding error if hiera cannot parse the yaml data" do expect do data_binder.find(request('invalid')) end.to raise_error(Puppet::DataBinding::LookupError) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_behaviours/file_server_terminus.rb
spec/shared_behaviours/file_server_terminus.rb
shared_examples_for "Puppet::Indirector::FileServerTerminus" do # This only works if the shared behaviour is included before # the 'before' block in the including context. before do Puppet::FileServing::Configuration.instance_variable_set(:@configuration, nil) allow(Puppet::FileSystem).to receive(:exist?).and_return(true) allow(Puppet::FileSystem).to receive(:exist?).with(Puppet[:fileserverconfig]).and_return(true) @path = Tempfile.new("file_server_testing") path = @path.path @path.close! @path = path Dir.mkdir(@path) File.open(File.join(@path, "myfile"), "w") { |f| f.print "my content" } # Use a real mount, so the integration is a bit deeper. @mount1 = Puppet::FileServing::Configuration::Mount::File.new("one") @mount1.path = @path @parser = double('parser', :changed? => false) allow(@parser).to receive(:parse).and_return("one" => @mount1) allow(Puppet::FileServing::Configuration::Parser).to receive(:new).and_return(@parser) # Stub out the modules terminus @modules = double('modules terminus') @request = Puppet::Indirector::Request.new(:indirection, :method, "puppet://myhost/one/myfile", nil) end it "should use the file server configuration to find files" do allow(@modules).to receive(:find).and_return(nil) allow(@terminus.indirection).to receive(:terminus).with(:modules).and_return(@modules) expect(@terminus.find(@request)).to be_instance_of(@test_class) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_behaviours/documentation_on_faces.rb
spec/shared_behaviours/documentation_on_faces.rb
# encoding: UTF-8 shared_examples_for "documentation on faces" do defined?(Attrs) or Attrs = [:summary, :description, :examples, :short_description, :notes, :author] defined?(SingleLineAttrs) or SingleLineAttrs = [:summary, :author] # Simple, procedural tests that apply to a bunch of methods. Attrs.each do |attr| it "should accept a #{attr}" do expect { subject.send("#{attr}=", "hello") }.not_to raise_error expect(subject.send(attr)).to eq("hello") end it "should accept a long (single line) value for #{attr}" do text = "I never know when to stop with the word banana" + ("na" * 1000) expect { subject.send("#{attr}=", text) }.to_not raise_error expect(subject.send(attr)).to eq(text) end end Attrs.each do |getter| setter = "#{getter}=".to_sym context "#{getter}" do it "should strip leading whitespace on a single line" do subject.send(setter, " death to whitespace") expect(subject.send(getter)).to eq("death to whitespace") end it "should strip trailing whitespace on a single line" do subject.send(setter, "death to whitespace ") expect(subject.send(getter)).to eq("death to whitespace") end it "should strip whitespace at both ends at once" do subject.send(setter, " death to whitespace ") expect(subject.send(getter)).to eq("death to whitespace") end multiline_text = "with\nnewlines" if SingleLineAttrs.include? getter then it "should not accept multiline values" do expect { subject.send(setter, multiline_text) }. to raise_error ArgumentError, /#{getter} should be a single line/ expect(subject.send(getter)).to be_nil end else it "should accept multiline values" do expect { subject.send(setter, multiline_text) }.not_to raise_error expect(subject.send(getter)).to eq(multiline_text) end [1, 2, 4, 7, 25].each do |length| context "#{length} chars indent" do indent = ' ' * length it "should strip leading whitespace on multiple lines" do text = "this\nis\the\final\outcome" subject.send(setter, text.gsub(/^/, indent)) expect(subject.send(getter)).to eq(text) end it "should not remove formatting whitespace, only global indent" do text = "this\n is\n the\n ultimate\ntest" subject.send(setter, text.gsub(/^/, indent)) expect(subject.send(getter)).to eq(text) end end end it "should strip whitespace with a blank line" do subject.send(setter, " this\n\n should outdent") expect(subject.send(getter)).to eq("this\n\nshould outdent") end end end end describe "#short_description" do it "should return the set value if set after description" do subject.description = "hello\ngoodbye" subject.short_description = "whatever" expect(subject.short_description).to eq("whatever") end it "should return the set value if set before description" do subject.short_description = "whatever" subject.description = "hello\ngoodbye" expect(subject.short_description).to eq("whatever") end it "should return nothing if not set and no description" do expect(subject.short_description).to be_nil end it "should return the first paragraph of description if not set (where it is one line long)" do subject.description = "hello" expect(subject.short_description).to eq(subject.description) end it "should return the first paragraph of description if not set (where there is no paragraph break)" do subject.description = "hello\ngoodbye" expect(subject.short_description).to eq(subject.description) end it "should return the first paragraph of description if not set (where there is a paragraph break)" do subject.description = "hello\ngoodbye\n\nmore\ntext\nhere\n\nfinal\nparagraph" expect(subject.short_description).to eq("hello\ngoodbye") end it "should trim a very, very long first paragraph and add ellipsis" do line = "this is a very, very, very long long line full of text\n" subject.description = line * 20 + "\n\nwhatever, dude." expect(subject.short_description).to eq((line * 5).chomp + ' [...]') end it "should trim a very very long only paragraph even if it is followed by a new paragraph" do line = "this is a very, very, very long long line full of text\n" subject.description = line * 20 expect(subject.short_description).to eq((line * 5).chomp + ' [...]') end end describe "multiple authors" do authors = %w{John Paul George Ringo} context "in the DSL" do it "should support multiple authors" do authors.each {|name| subject.author name } expect(subject.authors).to match_array(authors) expect(subject.author).to eq(authors.join("\n")) end it "should reject author as an array" do expect { subject.author ["Foo", "Bar"] }. to raise_error ArgumentError, /author must be a string/ end end context "#author=" do it "should accept a single name" do subject.author = "Fred" expect(subject.author).to eq("Fred") end it "should accept an array of names" do subject.author = authors expect(subject.authors).to match_array(authors) expect(subject.author).to eq(authors.join("\n")) end it "should not append when set multiple times" do subject.author = "Fred" subject.author = "John" expect(subject.author).to eq("John") end it "should reject arrays with embedded newlines" do expect { subject.author = ["Fred\nJohn"] }. to raise_error ArgumentError, /author should be a single line/ end end end describe "#license" do it "should default to reserving rights" do expect(subject.license).to match(/All Rights Reserved/) end it "should accept an arbitrary license string on the object" do subject.license = "foo" expect(subject.license).to eq("foo") end end describe "#copyright" do it "should fail with just a name" do expect { subject.copyright("invalid") }. to raise_error ArgumentError, /copyright takes the owners names, then the years covered/ end [1997, "1997"].each do |year| it "should accept an entity name and a #{year.class.name} year" do subject.copyright("me", year) expect(subject.copyright).to match(/\bme\b/) expect(subject.copyright).to match(/#{year}/) end it "should accept multiple entity names and a #{year.class.name} year" do subject.copyright ["me", "you"], year expect(subject.copyright).to match(/\bme\b/) expect(subject.copyright).to match(/\byou\b/) expect(subject.copyright).to match(/#{year}/) end end ["1997-2003", "1997 - 2003", 1997..2003].each do |range| it "should accept a #{range.class.name} range of years" do subject.copyright("me", range) expect(subject.copyright).to match(/\bme\b/) expect(subject.copyright).to match(/1997-2003/) end it "should accept a #{range.class.name} range of years" do subject.copyright ["me", "you"], range expect(subject.copyright).to match(/\bme\b/) expect(subject.copyright).to match(/\byou\b/) expect(subject.copyright).to match(/1997-2003/) end end [[1997, 2003], ["1997", 2003], ["1997", "2003"]].each do |input| it "should accept the set of years #{input.inspect} in an array" do subject.copyright "me", input expect(subject.copyright).to match(/\bme\b/) expect(subject.copyright).to match(/1997, 2003/) end it "should accept the set of years #{input.inspect} in an array" do subject.copyright ["me", "you"], input expect(subject.copyright).to match(/\bme\b/) expect(subject.copyright).to match(/\byou\b/) expect(subject.copyright).to match(/1997, 2003/) end end it "should warn if someone does math accidentally on the range of years" do expect { subject.copyright "me", 1997-2003 }. to raise_error ArgumentError, /copyright with a year before 1970 is very strange; did you accidentally add or subtract two years\?/ end it "should accept complex copyright years" do years = [1997, 1999, 2000..2002, 2005].reverse subject.copyright "me", years expect(subject.copyright).to match(/\bme\b/) expect(subject.copyright).to match(/1997, 1999, 2000-2002, 2005/) end end # Things that are automatically generated. [:name, :options, :synopsis].each do |attr| describe "##{attr}" do it "should not allow you to set #{attr}" do expect(subject).not_to respond_to :"#{attr}=" end it "should have a #{attr}" do expect(subject.send(attr)).not_to be_nil end it "'s #{attr} should not be empty..." do expect(subject.send(attr)).not_to eq('') end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_behaviours/iterative_functions.rb
spec/shared_behaviours/iterative_functions.rb
shared_examples_for 'all iterative functions hash handling' do |func| it 'passes a hash entry as an array of the key and value' do catalog = compile_to_catalog(<<-MANIFEST) {a=>1}.#{func} |$v| { notify { "${v[0]} ${v[1]}": } } MANIFEST expect(catalog.resource(:notify, "a 1")).not_to be_nil end end shared_examples_for 'all iterative functions argument checks' do |func| it 'raises an error when used against an unsupported type' do expect do compile_to_catalog(<<-MANIFEST) 3.14.#{func} |$k, $v| { } MANIFEST end.to raise_error(Puppet::Error, /expects an Iterable value, got Float/) end it 'raises an error when called with any parameters besides a block' do expect do compile_to_catalog(<<-MANIFEST) [1].#{func}(1,2) |$v,$y| { } MANIFEST end.to raise_error(Puppet::Error, /expects (?:between 1 and 2 arguments|1 argument), got 3/) end it 'raises an error when called without a block' do expect do compile_to_catalog(<<-MANIFEST) [1].#{func} MANIFEST end.to raise_error(Puppet::Error, /expects a block/) end it 'raises an error when called with something that is not a block' do expect do compile_to_catalog(<<-MANIFEST) [1].#{func}(1,2) MANIFEST end.to raise_error(Puppet::Error, /expects (?:between 1 and 2 arguments|1 argument), got 3/) end it 'raises an error when called with a block with too many required parameters' do expect do compile_to_catalog(<<-MANIFEST) [1].#{func}() |$v1, $v2, $v3| { } MANIFEST end.to raise_error(Puppet::Error, /block expects(?: between 1 and)? 2 arguments, got 3/) end it 'raises an error when called with a block with too few parameters' do expect do compile_to_catalog(<<-MANIFEST) [1].#{func}() | | { } MANIFEST end.to raise_error(Puppet::Error, /block expects(?: between 1 and)? 2 arguments, got none/) end it 'does not raise an error when called with a block with too many but optional arguments' do expect do compile_to_catalog(<<-MANIFEST) [1].#{func}() |$v1, $v2, $v3=extra| { } MANIFEST end.to_not raise_error end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/examples/enc/regexp_nodes/regexp_nodes.rb
examples/enc/regexp_nodes/regexp_nodes.rb
#!/usr/bin/env ruby # = Synopsis # This is an external node classifier script, after # https://puppet.com/docs/puppet/latest/lang_write_functions_in_puppet.html # # = Usage # regexp_nodes.rb <host> # # = Description # This classifier implements filesystem autoloading: It looks through classes, # parameters, and environment subdirectories, looping through each file it # finds. Each file's contents are a regexp-per-line which, if they match the # hostname passed to the program as ARGV[0], sets a class, parameter value # or environment named the same thing as the file itself. At the end, the # resultant data structure is returned back to the puppet master process as # yaml. # # = Caveats # Since the files are read in directory order, multiple matches for a given # hostname in the parameters/ and environment/ subdirectories will return the # last-read value. (Multiple classes/ matches don't cause a problem; the # class is either incuded or it isn't) # # Unmatched hostnames in any of the environment/ files will cause 'production' # to be emitted; be aware of the complexity surrounding the interaction between # ENC and environments as discussed in https://projects.puppetlabs.com/issues/3910 # # = Examples # Based on the example files in the classes/ and parameters/ subdirectories # in the distribution, classes/database will set the 'database' class for # hosts matching %r{db\d{2}} (that is, 'db' followed by two digits) or with # 'mysql' anywhere in the hostname. Similarly, hosts beginning with 'www' or # 'web' or the hostname 'leterel' (my workstation) will be assigned the # 'webserver' class. # # Under parameters/ there is one subdirectory 'service' which # sets the a parameter called 'service' to the value 'prod' for production # hosts (whose hostnames always end with a three-digit code), 'qa' for # anything that starts with 'qa-' 'qa2-' or 'qa3-', and 'sandbox' for any # development machines whose hostnames start with 'dev-'. # # In the environment/ subdirectory, any hosts matching '^dev-' and a single # production host which serves as 'canary in the coal mine' will be put into # the development environment # # = Author # Eric Sorenson <eric@explosive.net> # we need yaml or there's not much point in going on require 'yaml' # Sets are like arrays but automatically de-duplicate elements require 'set' # set up some syslog logging require 'syslog' Syslog.open('extnodes', Syslog::LOG_PID | Syslog::LOG_NDELAY, Syslog::LOG_DAEMON) # change this to LOG_UPTO(Sysslog::LOG_DEBUG) if you want to see everything # but remember your syslog.conf needs to match this or messages will be filtered Syslog.mask = Syslog::LOG_UPTO(Syslog::LOG_INFO) # Helper method to log to syslog; we log at level debug if no level is specified # since those are the most frequent calls to this method def log(message,level=:debug) Syslog.send(level,message) end # set our workingdir to be the directory we're executed from, regardless # of parent's cwd, symlinks, etc. via handy Pathname.realpath method require 'pathname' p = Pathname.new(File.dirname(__FILE__)) WORKINGDIR = "#{p.realpath}" # This class holds all the methods for creating and accessing the properties # of an external node. There are really only two public methods: initialize # and a special version of to_yaml class ExternalNode # Make these instance variables get/set-able with eponymous methods attr_accessor :classes, :parameters, :environment, :hostname # initialize takes three arguments: # hostname:: usually passed in via ARGV[0] but it could be anything # classdir:: directory under WORKINGDIR to look for files named after # classes # parameterdir:: directory under WORKINGDIR to look for directories to set # parameters def initialize(hostname, classdir = 'classes/', parameterdir = 'parameters/', environmentdir = 'environment/') # instance variables that contain the lists of classes and parameters @classes = Set.new @parameters = Hash.new("unknown") # sets a default value of "unknown" @environment = "production" self.parse_argv(hostname) self.match_classes("#{WORKINGDIR}/#{classdir}") self.match_parameters("#{WORKINGDIR}/#{parameterdir}") self.match_environment("#{WORKINGDIR}/#{environmentdir}") end # private method called by initialize which sanity-checks our hostname. # good candidate for overriding in a subclass if you need different checks def parse_argv(hostname) if hostname =~ /^([-\w]+?)\.([-\w\.]+)/ # non-greedy up to the first . is hostname @hostname = $1 elsif hostname =~ /^([-\w]+)$/ # sometimes puppet's @name is just a name @hostname = hostname log("got shortname for [#{hostname}]") else log("didn't receive parsable hostname, got: [#{hostname}]",:err) exit(1) end end # to_yaml massages a copy of the object and outputs clean yaml so we don't # feed weird things back to puppet []< def to_yaml classes = self.classes.to_a if self.parameters.empty? # otherwise to_yaml prints "parameters: {}" parameters = nil else parameters = self.parameters end ({ 'classes' => classes, 'parameters' => parameters, 'environment' => environment}).to_yaml end # Private method that expects an absolute path to a file and a string to # match - it returns true if the string was matched by any of the lines in # the file def matched_in_patternfile?(filepath, matchthis) patternlist = [] begin File.open(filepath).each do |l| l.chomp! next if l =~ /^$/ next if l =~ /^#/ if l =~ /^\s*(\S+)/ m = Regexp.last_match log("found a non-comment line, transforming [#{l}] into [#{m[1]}]") l.gsub!(l,m[1]) else next l end pattern = %r{#{l}} patternlist << pattern log("appending [#{pattern}] to patternlist for [#{filepath}]") end rescue StandardError log("Problem reading #{filepath}: #{$!}",:err) exit(1) end log("list of patterns for #{filepath}: #{patternlist}") if matchthis =~ Regexp.union(patternlist) log("matched #{$~} in #{matchthis}, returning true") return true else # hostname didn't match anything in patternlist log("#{matchthis} unmatched, returning false") return nil end end # def # private method - takes a path to look for files, iterates through all # readable, regular files it finds, and matches this instance's @hostname # against each line; if any match, the class will be set for this node. def match_classes(fullpath) Dir.foreach(fullpath) do |patternfile| filepath = "#{fullpath}/#{patternfile}" next unless File.file?(filepath) and File.readable?(filepath) next if patternfile =~ /^\./ log("Attempting to match [#{@hostname}] in [#{filepath}]") if matched_in_patternfile?(filepath,@hostname) @classes << patternfile.to_s log("Appended #{patternfile} to classes instance variable") end end end # match_environment is similar to match_classes but it overwrites # any previously set value (usually just the default, 'production') # with a match def match_environment(fullpath) Dir.foreach(fullpath) do |patternfile| filepath = "#{fullpath}/#{patternfile}" next unless File.file?(filepath) and File.readable?(filepath) next if patternfile =~ /^\./ log("Attempting to match [#{@hostname}] in [#{filepath}]") if matched_in_patternfile?(filepath,@hostname) @environment = patternfile.to_s log("Wrote #{patternfile} to environment instance variable") end end end # Parameters are handled slightly differently; we make another level of # directories to get the parameter name, then use the names of the files # contained in there for the values of those parameters. # # ex: cat ./parameters/service/production # ^prodweb # would set parameters["service"] = "production" for prodweb001 def match_parameters(fullpath) Dir.foreach(fullpath) do |parametername| filepath = "#{fullpath}/#{parametername}" next if File.basename(filepath) =~ /^\./ # skip over dotfiles next unless File.directory?(filepath) and File.readable?(filepath) # skip over non-directories log("Considering contents of #{filepath}") Dir.foreach("#{filepath}") do |patternfile| secondlevel = "#{filepath}/#{patternfile}" log("Found parameters patternfile at #{secondlevel}") next unless File.file?(secondlevel) and File.readable?(secondlevel) log("Attempting to match [#{@hostname}] in [#{secondlevel}]") if matched_in_patternfile?(secondlevel, @hostname) @parameters[ parametername.to_s ] = patternfile.to_s log("Set @parameters[#{parametername}] = #{patternfile}") end end end end end # Logic for local hacks that don't fit neatly into the autoloading model can # happen as we initialize a subclass class MyExternalNode < ExternalNode def initialize(hostname, classdir = 'classes/', parameterdir = 'parameters/') super # Set "hostclass" parameter based on hostname, # stripped of leading environment prefix and numeric suffix if @hostname =~ /^(\w*?)-?(\D+)(\d{2,3})$/ match = Regexp.last_match hostclass = match[2] log("matched hostclass #{hostclass}") @parameters[ "hostclass" ] = hostclass else log("couldn't figure out class from #{@hostname}",:warning) end end end # Here we begin actual execution by calling methods defined above mynode = MyExternalNode.new(ARGV[0]) puts mynode.to_yaml
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/examples/nagios/check_puppet.rb
examples/nagios/check_puppet.rb
#!/usr/bin/env ruby require 'optparse' require 'sys/proctable' include Sys class CheckPuppet VERSION = '0.1' script_name = File.basename($0) # default options OPTIONS = { :statefile => "/opt/puppetlabs/puppet/cache/state/state.yaml", :process => "puppet", :interval => 30, } OptionParser.new do |o| o.set_summary_indent(' ') o.banner = "Usage: #{script_name} [OPTIONS]" o.define_head "The check_puppet Nagios plug-in checks that specified Puppet process is running and the state file is no older than specified interval." o.separator "" o.separator "Mandatory arguments to long options are mandatory for short options too." o.on( "-s", "--statefile=statefile", String, "The state file", "Default: #{OPTIONS[:statefile]}") { |op| OPTIONS[:statefile] = op } o.on( "-p", "--process=processname", String, "The process to check", "Default: #{OPTIONS[:process]}") { |op| OPTIONS[:process] = op } o.on( "-i", "--interval=value", Integer, "Default: #{OPTIONS[:interval]} minutes") { |op| OPTIONS[:interval] = op } o.separator "" o.on_tail("-h", "--help", "Show this help message.") do puts o exit end o.parse!(ARGV) end def check_proc unless ProcTable.ps.find { |p| p.name == OPTIONS[:process]} @proc = 2 else @proc = 0 end end def check_state # Set variables curt = Time.now intv = OPTIONS[:interval] * 60 # Check file time begin @modt = File.mtime("#{OPTIONS[:statefile]}") rescue @file = 3 end diff = (curt - @modt).to_i if diff > intv @file = 2 else @file = 0 end end def output_status case @file when 0 state = "state file status okay updated on " + @modt.strftime("%m/%d/%Y at %H:%M:%S") when 2 state = "state fille is not up to date and is older than #{OPTIONS[:interval]} minutes" when 3 state = "state file status unknown" end case @proc when 0 process = "process #{OPTIONS[:process]} is running" when 2 process = "process #{OPTIONS[:process]} is not running" end case when (@proc == 2 or @file == 2) status = "CRITICAL" exitcode = 2 when (@proc == 0 and @file == 0) status = "OK" exitcode = 0 else status = "UNKNOWN" exitcode = 3 end puts "PUPPET #{status}: #{process}, #{state}" exit(exitcode) end end cp = CheckPuppet.new cp.check_proc cp.check_state cp.output_status
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/hiera_puppet.rb
lib/hiera_puppet.rb
# frozen_string_literal: true Puppet.features.hiera? require 'hiera/scope' require_relative 'puppet' module HieraPuppet module_function def lookup(key, default, scope, override, resolution_type) scope = Hiera::Scope.new(scope) answer = hiera.lookup(key, default, scope, override, resolution_type) if answer.nil? raise Puppet::ParseError, _("Could not find data item %{key} in any Hiera data file and no default supplied") % { key: key } end answer end def parse_args(args) # Functions called from Puppet manifests like this: # # hiera("foo", "bar") # # Are invoked internally after combining the positional arguments into a # single array: # # func = function_hiera # func(["foo", "bar"]) # # Functions called from templates preserve the positional arguments: # # scope.function_hiera("foo", "bar") # # Deal with Puppet's special calling mechanism here. if args[0].is_a?(Array) args = args[0] end if args.empty? raise Puppet::ParseError, _("Please supply a parameter to perform a Hiera lookup") end key = args[0] default = args[1] override = args[2] [key, default, override] end def hiera @hiera ||= Hiera.new(:config => hiera_config) end def hiera_config config = {} config_file = hiera_config_file if config_file config = Hiera::Config.load(config_file) end config[:logger] = 'puppet' config end def hiera_config_file hiera_config = Puppet.settings[:hiera_config] if Puppet::FileSystem.exist?(hiera_config) hiera_config else Puppet.warning _("Config file %{hiera_config} not found, using Hiera defaults") % { hiera_config: hiera_config } nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet_x.rb
lib/puppet_x.rb
# frozen_string_literal: true # The Puppet Extensions Module. # # Submodules of this module should be named after the publisher (e.g. # 'user' part of a Puppet Module name). You should also add the module # name to avoid further conflicts in the same namespace. So the # structure should be # `lib/puppet_x/<namespace>/<module_name>/<extension.rb>`. # A Puppet Extension for 'puppetlabs-powershell' would live at # `lib/puppet_x/puppetlabs/powershell/<extension.rb>`. # # @api public # module PuppetX end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet_pal.rb
lib/puppet_pal.rb
# frozen_string_literal: true # Puppet as a Library "PAL" # This is the entry point when using PAL as a standalone library. # # This requires all of puppet because 'settings' and many other things are still required in PAL. # Eventually that will not be the case. # require_relative 'puppet' require_relative 'puppet/pal/pal_api'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet.rb
lib/puppet.rb
# frozen_string_literal: true require_relative 'puppet/version' require_relative 'puppet/concurrent/synchronized' Puppet::OLDEST_RECOMMENDED_RUBY_VERSION = '3.1.0' if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new(Puppet::OLDEST_RECOMMENDED_RUBY_VERSION) raise LoadError, "Puppet #{Puppet.version} requires Ruby #{Puppet::OLDEST_RECOMMENDED_RUBY_VERSION} or greater, found Ruby #{RUBY_VERSION.dup}." end $LOAD_PATH.extend(Puppet::Concurrent::Synchronized) # see the bottom of the file for further inclusions # Also see the new Vendor support - towards the end # require_relative 'puppet/error' require_relative 'puppet/util' require_relative 'puppet/util/autoload' require_relative 'puppet/settings' require_relative 'puppet/util/feature' require_relative 'puppet/util/suidmanager' require_relative 'puppet/util/run_mode' require_relative 'puppet/gettext/config' require_relative 'puppet/defaults' # Defines the `Puppet` module. There are different entry points into Puppet # depending on your use case. # # To use puppet as a library, see {Puppet::Pal}. # # To create a new application, see {Puppet::Application}. # # To create a new function, see {Puppet::Functions}. # # To access puppet's REST APIs, see https://puppet.com/docs/puppet/latest/http_api/http_api_index.html. # # @api public module Puppet require_relative 'puppet/file_system' require_relative 'puppet/etc' require_relative 'puppet/context' require_relative 'puppet/environments' class << self Puppet::GettextConfig.setup_locale Puppet::GettextConfig.create_default_text_domain include Puppet::Util attr_reader :features end # the hash that determines how our system behaves @@settings = Puppet::Settings.new # 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. def self.settings @@settings end # The puppetserver project has its own settings class that is thread-aware; this # method is here to allow the puppetserver to define its own custom settings class # for multithreaded puppet. It is not intended for use outside of the puppetserver # implmentation. def self.replace_settings_object(new_settings) @@settings = new_settings end # Get the value for a setting # # @param [Symbol] param the setting to retrieve # # @api public def self.[](param) if param == :debug Puppet::Util::Log.level == :debug else @@settings[param] end end require_relative 'puppet/util/logging' extend Puppet::Util::Logging # The feature collection @features = Puppet::Util::Feature.new('puppet/feature') # Load the base features. require_relative 'puppet/feature/base' # setting access and stuff def self.[]=(param, value) @@settings[param] = value end def self.clear @@settings.clear end def self.debug=(value) if value Puppet::Util::Log.level = (:debug) else Puppet::Util::Log.level = (:notice) end end 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 # Modify the settings with defaults defined in `initialize_default_settings` method in puppet/defaults.rb. This can # be used in the initialization of new Puppet::Settings objects in the puppetserver project. Puppet.initialize_default_settings!(settings) # Now that settings are loaded we have the code loaded to be able to issue # deprecation warnings. Warn if we're on a deprecated ruby version. # Update JRuby version constraints in PUP-11716 if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new(Puppet::OLDEST_RECOMMENDED_RUBY_VERSION) Puppet.deprecation_warning(_("Support for ruby version %{version} is deprecated and will be removed in a future release. See https://puppet.com/docs/puppet/latest/system_requirements.html for a list of supported ruby versions.") % { version: RUBY_VERSION }) end # 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 # @param require_config [Boolean] controls loading of Puppet configuration files # @param global_settings [Boolean] controls push to global context after settings object initialization # @param runtime_implementations [Hash<Symbol, Object>] runtime implementations to register # @return [void] def self.initialize_settings(args = [], require_config = true, push_settings_globally = true, runtime_implementations = {}) do_initialize_settings_for_run_mode(:user, args, require_config, push_settings_globally, runtime_implementations) end def self.vendored_modules dir = Puppet[:vendormoduledir] if dir && File.directory?(dir) Dir.entries(dir) .reject { |f| f =~ /^\./ } .map { |f| File.join(dir, f, "lib") } .select { |d| FileTest.directory?(d) } else [] end end private_class_method :vendored_modules def self.initialize_load_path $LOAD_PATH.unshift(Puppet[:libdir]) $LOAD_PATH.concat(vendored_modules) end private_class_method :initialize_load_path # private helper method to provide the implementation details of initializing for a run mode, # but allowing us to control where the deprecation warning is issued def self.do_initialize_settings_for_run_mode(run_mode, args, require_config, push_settings_globally, runtime_implementations) Puppet.settings.initialize_global_settings(args, require_config) run_mode = Puppet::Util::RunMode[run_mode] Puppet.settings.initialize_app_defaults(Puppet::Settings.app_defaults_for_run_mode(run_mode)) if push_settings_globally initialize_load_path push_context_global(Puppet.base_context(Puppet.settings), "Initial context after settings initialization") Puppet::Parser::Functions.reset end runtime_implementations.each_pair do |name, impl| Puppet.runtime[name] = impl end end private_class_method :do_initialize_settings_for_run_mode # Initialize puppet's core facts. It should not be called before initialize_settings. def self.initialize_facts # Add the puppetversion fact; this is done before generating the hash so it is # accessible to custom facts. Puppet.runtime[:facter].add(:puppetversion) do setcode { Puppet.version.to_s } end Puppet.runtime[:facter].add(:agent_specified_environment) do setcode do Puppet.settings.set_by_cli(:environment) || Puppet.settings.set_in_section(:environment, :agent) || Puppet.settings.set_in_section(:environment, :main) end end end # Load vendored (setup paths, and load what is needed upfront). # See the Vendor class for how to add additional vendored gems/code require_relative 'puppet/vendor' Puppet::Vendor.load_vendored # The bindings used for initialization of puppet # # @param settings [Puppet::Settings,Hash<Symbol,String>] either a Puppet::Settings instance # or a Hash of settings key/value pairs. # @api private def self.base_context(settings) environmentpath = settings[:environmentpath] basemodulepath = Puppet::Node::Environment.split_path(settings[:basemodulepath]) if environmentpath.nil? || environmentpath.empty? raise(Puppet::Error, _("The environmentpath setting cannot be empty or nil.")) else loaders = Puppet::Environments::Directories.from_path(environmentpath, basemodulepath) # in case the configured environment (used for the default sometimes) # doesn't exist default_environment = Puppet[:environment].to_sym if default_environment == :production modulepath = settings[:modulepath] modulepath = (modulepath.nil? || '' == modulepath) ? basemodulepath : Puppet::Node::Environment.split_path(modulepath) loaders << Puppet::Environments::StaticPrivate.new( Puppet::Node::Environment.create(default_environment, modulepath, Puppet::Node::Environment::NO_MANIFEST) ) end end { :environments => Puppet::Environments::Cached.new(Puppet::Environments::Combined.new(*loaders)), :ssl_context => proc { Puppet.runtime[:http].default_ssl_context }, :http_session => proc { Puppet.runtime[:http].create_session }, :plugins => proc { Puppet::Plugins::Configuration.load_plugins }, :rich_data => Puppet[:rich_data], # `stringify_rich` controls whether `rich_data` is stringified into a lossy format # instead of a lossless format. Catalogs should not be stringified, though to_yaml # and the resource application have uses for a lossy, user friendly format. :stringify_rich => false } end # 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 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 # @param overrides [Hash] A hash of bindings to be merged with the parent context. # @param description [String] A description of the context. # @api private def self.push_context(overrides, description = "") @context.push(overrides, description) end # Push something onto the context and make it global across threads. This # has the potential to convert threadlocal overrides earlier on the stack into # global overrides. # @api private def self.push_context_global(overrides, description = '') @context.unsafe_push_global(overrides, description) end # Return to the previous context. # @raise [StackUnderflow] if the current context is the root # @api private def self.pop_context @context.pop end # Lookup a binding by name or return a default value provided by a passed block (if given). # @api private def self.lookup(name, &block) @context.lookup(name, &block) end # @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 def self.override(bindings, description = "", &block) @context.override(bindings, description, &block) end # @param name The name of a context key to ignore; intended for test usage. # @api private def self.ignore(name) @context.ignore(name) end # @param name The name of a previously ignored context key to restore; intended for test usage. # @api private def self.restore(name) @context.restore(name) end # @api private def self.mark_context(name) @context.mark(name) end # @api private def self.rollback_context(name) @context.rollback(name) end def self.runtime @runtime end require_relative 'puppet/node' # The single instance used for normal operation @context = Puppet::Context.new(bootstrap_context) require_relative 'puppet/runtime' @runtime = Puppet::Runtime.instance end # This feels weird to me; I would really like for us to get to a state where there is never a "require" statement # anywhere besides the very top of a file. That would not be possible at the moment without a great deal of # effort, but I think we should strive for it and revisit this at some point. --cprice 2012-03-16 require_relative 'puppet/indirector' require_relative 'puppet/compilable_resource_type' require_relative 'puppet/type' require_relative 'puppet/resource' require_relative 'puppet/parser' require_relative 'puppet/network' require_relative 'puppet/x509' require_relative 'puppet/ssl' require_relative 'puppet/module' require_relative 'puppet/data_binding' require_relative 'puppet/util/storage' require_relative 'puppet/file_bucket/file' require_relative 'puppet/plugins/configuration' require_relative 'puppet/pal/pal_api' require_relative 'puppet/node/facts'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/hiera/puppet_function.rb
lib/hiera/puppet_function.rb
# frozen_string_literal: true require 'hiera_puppet' # Provides the base class for the puppet functions hiera, hiera_array, hiera_hash, and hiera_include. # The actual function definitions will call init_dispatch and override the merge_type and post_lookup methods. # # @see hiera_array.rb, hiera_include.rb under lib/puppet/functions for sample usage # class Hiera::PuppetFunction < Puppet::Functions::InternalFunction def self.init_dispatch dispatch :hiera_splat do scope_param param 'Tuple[String, Any, Any, 1, 3]', :args end dispatch :hiera_no_default do scope_param param 'String', :key end dispatch :hiera_with_default do scope_param param 'String', :key param 'Any', :default optional_param 'Any', :override end dispatch :hiera_block1 do scope_param param 'String', :key block_param 'Callable[1,1]', :default_block end dispatch :hiera_block2 do scope_param param 'String', :key param 'Any', :override block_param 'Callable[1,1]', :default_block end end def hiera_splat(scope, args) hiera(scope, *args) end def hiera_no_default(scope, key) post_lookup(scope, key, lookup(scope, key, nil, false, nil)) end def hiera_with_default(scope, key, default, override = nil) post_lookup(scope, key, lookup(scope, key, default, true, override)) end def hiera_block1(scope, key, &default_block) post_lookup(scope, key, lookup(scope, key, nil, false, nil, &default_block)) end def hiera_block2(scope, key, override, &default_block) post_lookup(scope, key, lookup(scope, key, nil, false, override, &default_block)) end def lookup(scope, key, default, has_default, override, &default_block) unless Puppet[:strict] == :off # TRANSLATORS 'lookup' is a puppet function and should not be translated message = _("The function '%{class_name}' is deprecated in favor of using 'lookup'.") % { class_name: self.class.name } message += ' ' + _("See https://puppet.com/docs/puppet/%{minor_version}/deprecated_language.html") % { minor_version: Puppet.minor_version } Puppet.warn_once('deprecations', self.class.name, message) end lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}) adapter = lookup_invocation.lookup_adapter lookup_invocation.set_hiera_xxx_call lookup_invocation.set_global_only unless adapter.global_only? || adapter.has_environment_data_provider?(lookup_invocation) lookup_invocation.set_hiera_v3_location_overrides(override) unless override.nil? || override.is_a?(Array) && override.empty? Puppet::Pops::Lookup.lookup(key, nil, default, has_default, merge_type, lookup_invocation, &default_block) end def merge_type :first end def post_lookup(scope, key, result) result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/hiera/scope.rb
lib/hiera/scope.rb
# frozen_string_literal: true require 'forwardable' class Hiera class Scope extend Forwardable CALLING_CLASS = 'calling_class' CALLING_CLASS_PATH = 'calling_class_path' CALLING_MODULE = 'calling_module' MODULE_NAME = 'module_name' CALLING_KEYS = [CALLING_CLASS, CALLING_CLASS_PATH, CALLING_MODULE].freeze EMPTY_STRING = '' attr_reader :real def initialize(real) @real = real end def [](key) case key when CALLING_CLASS ans = find_hostclass(@real) when CALLING_CLASS_PATH ans = find_hostclass(@real).gsub(/::/, '/') when CALLING_MODULE ans = safe_lookupvar(MODULE_NAME) else ans = safe_lookupvar(key) end ans == EMPTY_STRING ? nil : ans end # This method is used to handle the throw of :undefined_variable since when # strict variables is not in effect, missing handling of the throw leads to # a more expensive code path. # def safe_lookupvar(key) reason = catch :undefined_variable do return @real.lookupvar(key) end case Puppet[:strict] when :off # do nothing when :warning Puppet.warn_once(Puppet::Parser::Scope::UNDEFINED_VARIABLES_KIND, _("Variable: %{name}") % { name: key }, _("Undefined variable '%{name}'; %{reason}") % { name: key, reason: reason }) when :error raise ArgumentError, _("Undefined variable '%{name}'; %{reason}") % { name: key, reason: reason } end nil end private :safe_lookupvar def exist?(key) CALLING_KEYS.include?(key) || @real.exist?(key) end def include?(key) CALLING_KEYS.include?(key) || @real.include?(key) end def catalog @real.catalog end def resource @real.resource end def compiler @real.compiler end def find_hostclass(scope) if scope.source and scope.source.type == :hostclass scope.source.name.downcase elsif scope.parent find_hostclass(scope.parent) else nil end end private :find_hostclass # This is needed for type conversion to work def_delegators :@real, :call_function end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider.rb
lib/puppet/provider.rb
# frozen_string_literal: true # 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 {instances}, {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). # # @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. # # @api public # class Puppet::Provider include Puppet::Util include Puppet::Util::Errors include Puppet::Util::Warnings extend Puppet::Util::Warnings require_relative '../puppet/confiner' require_relative 'provider/command' extend Puppet::Confiner Puppet::Util.logmethods(self, true) class << self # Include the util module so we have access to things like 'which' include Puppet::Util, Puppet::Util::Docs include Puppet::Util::Logging # @return [String] The name of the provider attr_accessor :name # # @todo Original = _"The source parameter exists so that providers using the same # source can specify this, so reading doesn't attempt to read the # same package multiple times."_ This seems to be a package type specific attribute. Is this really # used? # # @return [???] The source is WHAT? attr_writer :source # @todo What is this type? A reference to a Puppet::Type ? # @return [Puppet::Type] the resource type (that this provider is ... WHAT?) # attr_accessor :resource_type # @!attribute [r] doc # 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). # # @return [String] Returns the full documentation for the provider. # @see Puppet::Utils::Docs # @comment This is puzzling ... a write only doc attribute??? The generated setter never seems to be # used, instead the instance variable @doc is set in the `desc` method. This seems wrong. It is instead # documented as a read only attribute (to get the full documentation). Also see doc below for # desc. # @!attribute [w] desc # Sets the documentation of this provider class. (The full documentation is read via the # {doc} attribute). # # @dsl type # attr_writer :doc end # @return [???] This resource is what? Is an instance of a provider attached to one particular Puppet::Resource? # attr_accessor :resource # Convenience methods - see class method with the same name. # @return (see self.execute) def execute(*args) Puppet::Util::Execution.execute(*args) end # (see Puppet::Util::Execution.execute) def self.execute(*args) Puppet::Util::Execution.execute(*args) end # Convenience methods - see class method with the same name. # @return (see self.execpipe) def execpipe(*args, &block) Puppet::Util::Execution.execpipe(*args, &block) end # (see Puppet::Util::Execution.execpipe) def self.execpipe(*args, &block) Puppet::Util::Execution.execpipe(*args, &block) end # Returns the absolute path to the executable for the command referenced by the given name. # @raise [Puppet::DevError] if the name does not reference an existing command. # @return [String] the absolute path to the found executable for the command # @see which # @api public def self.command(name) name = name.intern command = @commands[name] if defined?(@commands) command = superclass.command(name) if !command && superclass.respond_to?(:command) unless command raise Puppet::DevError, _("No command %{command} defined for provider %{provider}") % { command: name, provider: self.name } end which(command) end # Confines this provider to be suitable only on hosts where the given commands are present. # Also see {Puppet::Confiner#confine} for other types of confinement of a provider by use of other types of # predicates. # # @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. # # @param 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. # @return [void] # @see optional_commands # @api public # def self.commands(command_specs) command_specs.each do |name, path| has_command(name, path) end end # 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. # @param [Hash{String => String}] hash 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 #has_command) # @see commands # @api public def self.optional_commands(hash) hash.each do |name, target| has_command(name, target) do is_optional end end end # 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. # # @example Use it like this: # has_command(:echo, "/bin/echo") # def some_method # echo("arg 1", "arg 2") # end # @comment the . . . below is intentional to avoid the three dots to become an illegible ellipsis char. # @example . . . or like this # has_command(:echo, "/bin/echo") do # is_optional # environment :HOME => "/var/tmp", :PWD => "/tmp" # end # # @param name [Symbol] The name of the command (will become the name of the generated method that executes the command) # @param path [String] The path to the executable for the command # @yield [ ] A block that configures the command (see {Puppet::Provider::Command}) # @comment a yield [ ] produces { ... } in the signature, do not remove the space. # @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. # @api public # rubocop:disable Naming/PredicateName 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 # rubocop:enable Naming/PredicateName # Internal helper class when creating commands - undocumented. # @api private class CommandDefiner private_class_method :new def self.define(name, path, confiner, &block) definer = new(name, path, confiner) definer.instance_eval(&block) if block definer.command end def initialize(name, path, confiner) @name = name @path = path @optional = false @confiner = confiner @custom_environment = {} end def is_optional # rubocop:disable Naming/PredicateName @optional = true end def environment(env) @custom_environment = @custom_environment.merge(env) end def command unless @optional @confiner.confine :exists => @path, :for_binary => true end Puppet::Provider::Command.new(@name, @path, Puppet::Util, Puppet::Util::Execution, { :failonfail => true, :combine => true, :custom_environment => @custom_environment }) end end # @return [Boolean] Return whether the given feature has been declared or not. def self.declared_feature?(name) defined?(@declared_features) and @declared_features.include?(name) end # @return [Boolean] Returns whether this implementation satisfies all of the default requirements or not. # Returns false if there is no matching defaultfor # @see Provider.defaultfor # def self.default? default_match ? true : false end # Look through the array of defaultfor hashes and return the first match. # @return [Hash<{String => Object}>] the matching hash specified by a defaultfor # @see Provider.defaultfor # @api private def self.default_match return nil if some_default_match(@notdefaults) # Blacklist means this provider cannot be a default some_default_match(@defaults) end def self.some_default_match(defaultlist) defaultlist.find do |default| default.all? do |key, values| key == :feature ? feature_match(values) : fact_match(key, values) end end end # Compare a fact value against one or more supplied value # @param [Symbol] fact a fact to query to match against one of the given values # @param [Array, Regexp, String] values one or more values to compare to the # value of the given fact # @return [Boolean] whether or not the fact value matches one of the supplied # values. Given one or more Regexp instances, fact is compared via the basic # pattern-matching operator. def self.fact_match(fact, values) fact_val = Puppet.runtime[:facter].value(fact).to_s.downcase if fact_val.empty? false else values = [values] unless values.is_a?(Array) values.any? do |value| if value.is_a?(Regexp) fact_val =~ value else fact_val.intern == value.to_s.downcase.intern end end end end def self.feature_match(value) Puppet.features.send(value.to_s + "?") end # 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). # @param hash [Hash<{String => Object}>] hash of fact name to fact value. # @return [void] # def self.defaultfor(hash) @defaults << hash end def self.notdefaultfor(hash) @notdefaults << hash end # @return [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. # The number of requirements is based on the hash size of the matching {Provider.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). # @note Because of how this value is # calculated there could be surprising side effects if a provider included an excessive amount of classes. # 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 # Initializes defaults and commands (i.e. clears them). # @return [void] def self.initvars @defaults = [] @notdefaults = [] @commands = {} end # 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. # # @note The returned instances are instance of some subclass of Provider, not resources. # @return [Array<Puppet::Provider>] a list of providers referencing the system entities # @abstract this method must be implemented by a subclass and this super method should never be called as it raises an exception. # @raise [Puppet::DevError] Error indicating that the method should have been implemented by subclass. # @see prefetch def self.instances raise Puppet::DevError, _("To support listing resources of this type the '%{provider}' provider needs to implement an 'instances' class method returning the current set of resources. We recommend porting your module to the simpler Resource API instead: https://puppet.com/search/docs?keys=resource+api") % { provider: name } end # 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`. # # @return [void] # 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 initvars # This method is used to generate a method for a command. # @return [void] # @api private # def self.create_class_and_instance_method(name, &block) unless singleton_class.method_defined?(name) meta_def(name, &block) end unless method_defined?(name) define_method(name) do |*args| self.class.send(name, *args) end end end private_class_method :create_class_and_instance_method # @return [String] Returns the data source, which is the provider name if no other source has been set. # @todo Unclear what "the source" is used for? def self.source @source ||= name end # 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. # # @param param [Class, Puppet::Parameter] the parameter class, or a parameter instance # @return [Boolean] Returns whether this provider supports the given parameter or not. # @raise [Puppet::DevError] if the given parameter is not valid for the resource type # def self.supports_parameter?(param) if param.is_a?(Class) klass = param else klass = resource_type.attrclass(param) unless klass raise Puppet::DevError, _("'%{parameter_name}' is not a valid parameter for %{resource_type}") % { parameter_name: param, resource_type: resource_type.name } end end features = klass.required_features return true unless features !!satisfies?(*features) end dochook(:defaults) do if @defaults.length > 0 return @defaults.collect do |d| "Default for " + d.collect do |f, v| "`#{f}` == `#{[v].flatten.join(', ')}`" end.sort.join(" and ") + "." end.join(" ") end end dochook(:commands) do if @commands.length > 0 return "Required binaries: " + @commands.collect do |_n, c| "`#{c}`" end.sort.join(", ") + "." end end dochook(:features) do if features.length > 0 return "Supported features: " + features.collect do |f| "`#{f}`" end.sort.join(", ") + "." end end # Clears this provider instance to allow GC to clean up. def clear @resource = nil end # (see command) def command(name) self.class.command(name) end # Returns the value of a parameter value, or `:absent` if it is not defined. # @param param [Puppet::Parameter] the parameter to obtain the value of # @return [Object] the value of the parameter or `:absent` if not defined. # def get(param) @property_hash[param.intern] || :absent end # 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). # # @todo The use of a hash as a parameter needs a better explanation; why is this done? What is the intent? # @param resource [Puppet::Resource, Hash] optional resource or hash # 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 # Returns the name of the resource this provider is operating on. # @return [String] the name of the resource instance (e.g. the file path of a File). # @raise [Puppet::DevError] if no resource is set, or no name defined. # def name n = @property_hash[:name] if n n elsif resource resource.name else raise Puppet::DevError, _("No resource and no name in property hash in %{class_name} instance") % { class_name: self.class.name } end end # Sets the given parameters values as the current values for those parameters. # Other parameters are unchanged. # @param [Array<Puppet::Parameter>] params the parameters with values that should be set # @return [void] # def set(params) params.each do |param, value| @property_hash[param.intern] = value end end # @return [String] Returns a human readable string with information about the resource and the provider. def to_s "#{@resource}(provider=#{self.class.name})" end # @return [String] Returns a human readable string with information about the resource and the provider. def inspect to_s end # Makes providers comparable. include Comparable # 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. # # @return [-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 Comparable 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. self.class.name <=> other.class.name end # @comment Document prefetch here as it does not exist anywhere else (called from transaction if implemented) # @!method self.prefetch(resource_hash) # @abstract A subclass may implement this - it is not implemented in the Provider class # 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). # @param resources_hash [Hash<{String => Puppet::Resource}>] map from name to resource of resources to prefetch # @return [void] # @api public # @comment Document post_resource_eval here as it does not exist anywhere else (called from transaction if implemented) # @!method self.post_resource_eval() # @since 3.4.0 # @api public # @abstract A subclass may implement this - it is not implemented in the Provider class # 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. # @return [void] # @comment Document flush here as it does not exist anywhere (called from transaction if implemented) # @!method flush() # @abstract A subclass may implement this - it is not implemented in the Provider class # 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. # @return [void] # @api public end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/plugins.rb
lib/puppet/plugins.rb
# frozen_string_literal: true # The Puppet Plugins module defines extension points where plugins can be configured # to add or modify puppet's behavior. See the respective classes in this module for more # details. # # @api public # @since Puppet 4.0.0 # module Puppet::Plugins end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_serving.rb
lib/puppet/file_serving.rb
# frozen_string_literal: true # Just a stub class. class Puppet::FileServing # :nodoc: end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/agent.rb
lib/puppet/agent.rb
# frozen_string_literal: true require_relative '../puppet/application' require_relative '../puppet/error' require_relative '../puppet/util/at_fork' require 'timeout' # A general class for triggering a run of another # class. class Puppet::Agent require_relative 'agent/locker' include Puppet::Agent::Locker require_relative 'agent/disabler' include Puppet::Agent::Disabler require_relative '../puppet/util/splayer' include Puppet::Util::Splayer # Special exception class used to signal an agent run has timed out. class RunTimeoutError < Exception # rubocop:disable Lint/InheritException end attr_reader :client_class, :client, :should_fork def initialize(client_class, should_fork = true) @should_fork = can_fork? && should_fork @client_class = client_class end def can_fork? Puppet.features.posix? && RUBY_PLATFORM != 'java' end def needing_restart? Puppet::Application.restart_requested? end # Perform a run with our client. def run(client_options = {}) if disabled? log_disabled_message return end result = nil wait_for_lock_deadline = nil block_run = Puppet::Application.controlled_run do # splay may sleep for awhile when running onetime! If not onetime, then # the job scheduler splays (only once) so that agents assign themselves a # slot within the splay interval. do_splay = client_options.fetch(:splay, Puppet[:splay]) if do_splay splay(do_splay) if disabled? log_disabled_message break end end # waiting for certs may sleep for awhile depending on onetime, waitforcert and maxwaitforcert! # this needs to happen before forking so that if we fail to obtain certs and try to exit, then # we exit the main process and not the forked child. ssl_context = wait_for_certificates(client_options) result = run_in_fork(should_fork) do with_client(client_options[:transaction_uuid], client_options[:job_id]) do |client| client_args = client_options.merge(:pluginsync => Puppet::Configurer.should_pluginsync?) begin # lock may sleep for awhile depending on waitforlock and maxwaitforlock! lock do if disabled? log_disabled_message nil else # NOTE: Timeout is pretty heinous as the location in which it # throws an error is entirely unpredictable, which means that # it can interrupt code blocks that perform cleanup or enforce # sanity. The only thing a Puppet agent should do after this # error is thrown is die with as much dignity as possible. Timeout.timeout(Puppet[:runtimeout], RunTimeoutError) do Puppet.override(ssl_context: ssl_context) do client.run(client_args) end end end end rescue Puppet::LockError now = Time.now.to_i wait_for_lock_deadline ||= now + Puppet[:maxwaitforlock] if Puppet[:waitforlock] < 1 Puppet.notice _("Run of %{client_class} already in progress; skipping (%{lockfile_path} exists)") % { client_class: client_class, lockfile_path: lockfile_path } nil elsif now >= wait_for_lock_deadline Puppet.notice _("Exiting now because the maxwaitforlock timeout has been exceeded.") nil else Puppet.info _("Another puppet instance is already running; --waitforlock flag used, waiting for running instance to finish.") Puppet.info _("Will try again in %{time} seconds.") % { time: Puppet[:waitforlock] } sleep Puppet[:waitforlock] retry end rescue RunTimeoutError => detail Puppet.log_exception(detail, _("Execution of %{client_class} did not complete within %{runtimeout} seconds and was terminated.") % { client_class: client_class, runtimeout: Puppet[:runtimeout] }) nil rescue StandardError => detail Puppet.log_exception(detail, _("Could not run %{client_class}: %{detail}") % { client_class: client_class, detail: detail }) nil ensure Puppet.runtime[:http].close end end end true end Puppet.notice _("Shutdown/restart in progress (%{status}); skipping run") % { status: Puppet::Application.run_status.inspect } unless block_run result end def stopping? Puppet::Application.stop_requested? end def run_in_fork(forking = true) return yield unless forking or Puppet.features.windows? atForkHandler = Puppet::Util::AtFork.get_handler atForkHandler.prepare begin child_pid = Kernel.fork do atForkHandler.child $0 = _("puppet agent: applying configuration") begin exit(yield || 1) rescue NoMemoryError exit(254) end end ensure atForkHandler.parent end exit_code = Process.waitpid2(child_pid) exit_code[1].exitstatus end private # Create and yield a client instance, keeping a reference # to it during the yield. def with_client(transaction_uuid, job_id = nil) begin @client = client_class.new(transaction_uuid, job_id) rescue StandardError => detail Puppet.log_exception(detail, _("Could not create instance of %{client_class}: %{detail}") % { client_class: client_class, detail: detail }) return end yield @client ensure @client = nil end def wait_for_certificates(options) waitforcert = options[:waitforcert] || (Puppet[:onetime] ? 0 : Puppet[:waitforcert]) sm = Puppet::SSL::StateMachine.new(waitforcert: waitforcert, onetime: Puppet[:onetime]) sm.ensure_client_certificate end def log_disabled_message Puppet.notice _("Skipping run of %{client_class}; administratively disabled (Reason: '%{disable_message}');\nUse 'puppet agent --enable' to re-enable.") % { client_class: client_class, disable_message: disable_message } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/resource.rb
lib/puppet/resource.rb
# frozen_string_literal: true require_relative '../puppet' require_relative '../puppet/util/tagging' require_relative '../puppet/parameter' # The simplest resource class. Eventually it will function as the # base class for all resource-like behaviour. # # @api public class Puppet::Resource include Puppet::Util::Tagging include Puppet::Util::PsychSupport include Enumerable attr_accessor :file, :line, :catalog, :exported, :virtual, :strict, :kind attr_reader :type, :title, :parameters # @!attribute [rw] sensitive_parameters # @api private # @return [Array<Symbol>] A list of parameters to be treated as sensitive attr_accessor :sensitive_parameters # @deprecated attr_accessor :validate_parameters require_relative '../puppet/indirector' extend Puppet::Indirector indirects :resource, :terminus_class => :ral EMPTY_ARRAY = [].freeze EMPTY_HASH = {}.freeze ATTRIBUTES = [:file, :line, :exported, :kind].freeze TYPE_CLASS = 'Class' TYPE_NODE = 'Node' CLASS_STRING = 'class' DEFINED_TYPE_STRING = 'defined_type' COMPILABLE_TYPE_STRING = 'compilable_type' UNKNOWN_TYPE_STRING = 'unknown' PCORE_TYPE_KEY = '__ptype' VALUE_KEY = 'value' def self.from_data_hash(data) resource = allocate resource.initialize_from_hash(data) resource end def initialize_from_hash(data) type = data['type'] raise ArgumentError, _('No resource type provided in serialized data') unless type title = data['title'] raise ArgumentError, _('No resource title provided in serialized data') unless title @type, @title = self.class.type_and_title(type, title) params = data['parameters'] if params params = Puppet::Pops::Serialization::FromDataConverter.convert(params) @parameters = {} params.each { |param, value| self[param] = value } else @parameters = EMPTY_HASH end sensitives = data['sensitive_parameters'] if sensitives @sensitive_parameters = sensitives.map(&:to_sym) else @sensitive_parameters = EMPTY_ARRAY end tags = data['tags'] if tags tag(*tags) end ATTRIBUTES.each do |a| value = data[a.to_s] send("#{a}=", value) unless value.nil? end end def inspect "#{@type}[#{@title}]#{to_hash.inspect}" end # Produces a Data compliant hash of the resource. # The result depends on the --rich_data setting, and the context value # for Puppet.lookup(:stringify_rich), that if it is `true` will use the # ToStringifiedConverter to produce the value per parameter. # (Note that the ToStringifiedConverter output is lossy and should not # be used when producing a catalog serialization). # def to_data_hash data = { 'type' => type, 'title' => title.to_s, 'tags' => tags.to_data_hash } ATTRIBUTES.each do |param| value = send(param) data[param.to_s] = value unless value.nil? end data['exported'] ||= false # To get stringified parameter values the flag :stringify_rich can be set # in the puppet context. # stringify = Puppet.lookup(:stringify_rich) converter = stringify ? Puppet::Pops::Serialization::ToStringifiedConverter.new : nil params = {} to_hash.each_pair do |param, value| # Don't duplicate the title as the namevar unless param == namevar && value == title if stringify params[param.to_s] = converter.convert(value) else params[param.to_s] = Puppet::Resource.value_to_json_data(value) end end end unless params.empty? data['parameters'] = Puppet::Pops::Serialization::ToDataConverter .convert(params, { :rich_data => Puppet.lookup(:rich_data), :symbol_as_string => true, :local_reference => false, :type_by_reference => true, :message_prefix => ref, :semantic => self }) end data['sensitive_parameters'] = sensitive_parameters.map(&:to_s) unless sensitive_parameters.empty? data end def self.value_to_json_data(value) if value.is_a?(Array) value.map { |v| value_to_json_data(v) } elsif value.is_a?(Hash) result = {} value.each_pair { |k, v| result[value_to_json_data(k)] = value_to_json_data(v) } result elsif value.is_a?(Puppet::Resource) value.to_s elsif value.is_a?(Symbol) && value == :undef nil else value end end def yaml_property_munge(x) value.to_json_data(x) end # Proxy these methods to the parameters hash. It's likely they'll # be overridden at some point, but this works for now. %w[has_key? keys length delete empty? <<].each do |method| define_method(method) do |*args| parameters.send(method, *args) end end # Set a given parameter. Converts all passed names # to lower-case symbols. def []=(param, value) validate_parameter(param) if validate_parameters parameters[parameter_name(param)] = value end # Return a given parameter's value. Converts all passed names # to lower-case symbols. def [](param) parameters[parameter_name(param)] end def ==(other) return false unless other.respond_to?(:title) and type == other.type and title == other.title return false unless to_hash == other.to_hash true end # Compatibility method. def builtin? # TODO: should be deprecated (was only used in one place in puppet codebase) builtin_type? end # Is this a builtin resource type? def builtin_type? # Note - old implementation only checked if the resource_type was a Class resource_type.is_a?(Puppet::CompilableResourceType) end def self.to_kind(resource_type) if resource_type == CLASS_STRING CLASS_STRING elsif resource_type.is_a?(Puppet::Resource::Type) && resource_type.type == :definition DEFINED_TYPE_STRING elsif resource_type.is_a?(Puppet::CompilableResourceType) COMPILABLE_TYPE_STRING else UNKNOWN_TYPE_STRING end end # Iterate over each param/value pair, as required for Enumerable. def each parameters.each { |p, v| yield p, v } end def include?(parameter) super || parameters.keys.include?(parameter_name(parameter)) end %w[exported virtual strict].each do |m| define_method(m + "?") do send(m) end end def class? @is_class ||= @type == TYPE_CLASS end def stage? @is_stage ||= @type.to_s.casecmp("stage").zero? end # Construct a resource from data. # # Constructs a resource instance with the given `type` and `title`. Multiple # type signatures are possible for these arguments and most will result in an # expensive call to {Puppet::Node::Environment#known_resource_types} in order # to resolve `String` and `Symbol` Types to actual Ruby classes. # # @param type [Symbol, String] The name of the Puppet Type, as a string or # symbol. The actual Type will be looked up using # {Puppet::Node::Environment#known_resource_types}. This lookup is expensive. # @param type [String] The full resource name in the form of # `"Type[Title]"`. This method of calling should only be used when # `title` is `nil`. # @param type [nil] If a `nil` is passed, the title argument must be a string # of the form `"Type[Title]"`. # @param type [Class] A class that inherits from `Puppet::Type`. This method # of construction is much more efficient as it skips calls to # {Puppet::Node::Environment#known_resource_types}. # # @param title [String, :main, nil] The title of the resource. If type is `nil`, may also # be the full resource name in the form of `"Type[Title]"`. # # @api public def initialize(type, title = nil, attributes = EMPTY_HASH) @parameters = {} @sensitive_parameters = [] if type.is_a?(Puppet::Resource) # Copy constructor. Let's avoid munging, extracting, tagging, etc src = type self.file = src.file self.line = src.line self.kind = src.kind self.exported = src.exported self.virtual = src.virtual set_tags(src) self.environment = src.environment @rstype = src.resource_type @type = src.type @title = src.title src.to_hash.each do |p, v| case v when Puppet::Resource v = v.copy_as_resource when Array # flatten resource references arrays v = v.flatten if v.flatten.find { |av| av.is_a?(Puppet::Resource) } v = v.collect do |av| av = av.copy_as_resource if av.is_a?(Puppet::Resource) av end end self[p] = v end @sensitive_parameters.replace(type.sensitive_parameters) else if type.is_a?(Hash) # TRANSLATORS 'Puppet::Resource.new' should not be translated raise ArgumentError, _("Puppet::Resource.new does not take a hash as the first argument.") + ' ' + _("Did you mean (%{type}, %{title}) ?") % { type: (type[:type] || type["type"]).inspect, title: (type[:title] || type["title"]).inspect } end # In order to avoid an expensive search of 'known_resource_types" and # to obey/preserve the implementation of the resource's type - if the # given type is a resource type implementation (one of): # * a "classic" 3.x ruby plugin # * a compatible implementation (e.g. loading from pcore metadata) # * a resolved user defined type # # ...then, modify the parameters to the "old" (agent side compatible) way # of describing the type/title with string/symbols. # # TODO: Further optimizations should be possible as the "type juggling" is # not needed when the type implementation is known. # if type.is_a?(Puppet::CompilableResourceType) || type.is_a?(Puppet::Resource::Type) # set the resource type implementation self.resource_type = type # set the type name to the symbolic name type = type.name end @exported = false # Set things like environment, strictness first. attributes.each do |attr, value| next if attr == :parameters send(attr.to_s + "=", value) end if environment.is_a?(Puppet::Node::Environment) && environment != Puppet::Node::Environment::NONE self.file = environment.externalize_path(attributes[:file]) end @type, @title = self.class.type_and_title(type, title) rt = resource_type self.kind = self.class.to_kind(rt) unless kind if strict? && rt.nil? if class? raise ArgumentError, _("Could not find declared class %{title}") % { title: title } else raise ArgumentError, _("Invalid resource type %{type}") % { type: type } end end params = attributes[:parameters] unless params.nil? || params.empty? extract_parameters(params) if rt && rt.respond_to?(:deprecate_params) rt.deprecate_params(title, params) end end tag(self.type) tag_if_valid(self.title) end end def ref to_s end # Find our resource. def resolve catalog ? catalog.resource(to_s) : nil end # The resource's type implementation # @return [Puppet::Type, Puppet::Resource::Type] # @api private def resource_type @rstype ||= self.class.resource_type(type, title, environment) end # The resource's type implementation # @return [Puppet::Type, Puppet::Resource::Type] # @api private def self.resource_type(type, title, environment) case type when TYPE_CLASS; environment.known_resource_types.hostclass(title == :main ? "" : title) when TYPE_NODE; environment.known_resource_types.node(title) else result = Puppet::Type.type(type) unless result krt = environment.known_resource_types result = krt.definition(type) end result end end # Set the resource's type implementation # @param type [Puppet::Type, Puppet::Resource::Type] # @api private def resource_type=(type) @rstype = type end def environment @environment ||= if catalog catalog.environment_instance else Puppet.lookup(:current_environment) { Puppet::Node::Environment::NONE } end end def environment=(environment) @environment = environment end # Produces a hash of attribute to value mappings where the title parsed into its components # acts as the default values overridden by any parameter values explicitly given as parameters. # def to_hash parse_title.merge parameters end def to_s "#{type}[#{title}]" end def uniqueness_key # Temporary kludge to deal with inconsistent use patterns; ensure we don't return nil for namevar/:name h = to_hash name = h[namevar] || h[:name] || self.name h[namevar] ||= name h[:name] ||= name h.values_at(*key_attributes.sort_by(&:to_s)) end def key_attributes resource_type.respond_to?(:key_attributes) ? resource_type.key_attributes : [:name] end # Convert our resource to yaml for Hiera purposes. # # @deprecated Use {to_hiera_hash} instead. def to_hierayaml # Collect list of attributes to align => and move ensure first attr = parameters.keys attr_max = attr.inject(0) { |max, k| k.to_s.length > max ? k.to_s.length : max } attr.sort! if attr.first != :ensure && attr.include?(:ensure) attr.delete(:ensure) attr.unshift(:ensure) end # rubocop:disable Lint/FormatParameterMismatch attributes = attr.collect { |k| v = parameters[k] " %-#{attr_max}s: %s\n" % [k, Puppet::Parameter.format_value_for_display(v)] }.join # rubocop:enable Lint/FormatParameterMismatch " %s:\n%s" % [title, attributes] end # Convert our resource to a hiera hash suitable for serialization. def to_hiera_hash # to_data_hash converts to safe Data types, e.g. no symbols, unicode replacement character h = to_data_hash params = h['parameters'] || {} value = params.delete('ensure') res = {} res['ensure'] = value if value res.merge!(params.sort.to_h) { h['title'] => res } end # Convert our resource to Puppet code. def to_manifest # Collect list of attributes to align => and move ensure first attr = parameters.keys attr_max = attr.inject(0) { |max, k| k.to_s.length > max ? k.to_s.length : max } attr.sort! if attr.first != :ensure && attr.include?(:ensure) attr.delete(:ensure) attr.unshift(:ensure) end # rubocop:disable Lint/FormatParameterMismatch attributes = attr.collect { |k| v = parameters[k] " %-#{attr_max}s => %s,\n" % [k, Puppet::Parameter.format_value_for_display(v)] }.join # rubocop:enable Lint/FormatParameterMismatch escaped = title.gsub(/'/, "\\\\'") "%s { '%s':\n%s}" % [type.to_s.downcase, escaped, attributes] end def to_ref ref end # Convert our resource to a RAL resource instance. Creates component # instances for resource types that are not of a compilable_type kind. In case # the resource doesn’t exist and it’s compilable_type kind, raise an error. # There are certain cases where a resource won't be in a catalog, such as # when we create a resource directly by using Puppet::Resource.new(...), so we # must check its kind before deciding whether the catalog format is of an older # version or not. def to_ral if kind == COMPILABLE_TYPE_STRING typeklass = Puppet::Type.type(type) elsif catalog && catalog.catalog_format >= 2 typeklass = Puppet::Type.type(:component) else typeklass = Puppet::Type.type(type) || Puppet::Type.type(:component) end raise(Puppet::Error, "Resource type '#{type}' was not found") unless typeklass typeklass.new(self) end def name # this is potential namespace conflict # between the notion of an "indirector name" # and a "resource name" [type, title].join('/') end def missing_arguments resource_type.arguments.select do |param, _default| the_param = parameters[param.to_sym] the_param.nil? || the_param.value.nil? || the_param.value == :undef end end private :missing_arguments def copy_as_resource Puppet::Resource.new(self) end def valid_parameter?(name) resource_type.valid_parameter?(name) end def validate_parameter(name) raise Puppet::ParseError.new(_("no parameter named '%{name}'") % { name: name }, file, line) unless valid_parameter?(name) end # This method, together with #file and #line, makes it possible for a Resource to be a 'source_pos' in a reported issue. # @return [Integer] Instances of this class will always return `nil`. def pos nil end def prune_parameters(options = EMPTY_HASH) properties = resource_type.properties.map(&:name) dup.collect do |attribute, value| if value.to_s.empty? or Array(value).empty? delete(attribute) elsif value.to_s == "absent" and attribute.to_s != "ensure" delete(attribute) end parameters_to_include = resource_type.parameters_to_include parameters_to_include += options[:parameters_to_include] || [] delete(attribute) unless properties.include?(attribute) || parameters_to_include.include?(attribute) end self end # @api private def self.type_and_title(type, title) type, title = extract_type_and_title(type, title) type = munge_type_name(type) if type == TYPE_CLASS title = title == '' ? :main : munge_type_name(title) end [type, title] end def self.extract_type_and_title(argtype, argtitle) if (argtype.nil? || argtype == :component || argtype == :whit) && argtitle =~ /^([^\[\]]+)\[(.+)\]$/m then [::Regexp.last_match(1), ::Regexp.last_match(2)] elsif argtitle.nil? && argtype.is_a?(String) && argtype =~ /^([^\[\]]+)\[(.+)\]$/m then [::Regexp.last_match(1), ::Regexp.last_match(2)] elsif argtitle then [argtype, argtitle] elsif argtype.is_a?(Puppet::Type) then [argtype.class.name, argtype.title] else raise ArgumentError, _("No title provided and %{type} is not a valid resource reference") % { type: argtype.inspect } # rubocop:disable Lint/ElseLayout end end private_class_method :extract_type_and_title def self.munge_type_name(value) return :main if value == :main return TYPE_CLASS if value == '' || value.nil? || value.to_s.casecmp('component') == 0 Puppet::Pops::Types::TypeFormatter.singleton.capitalize_segments(value.to_s) end private_class_method :munge_type_name private # Produce a canonical method name. def parameter_name(param) param = param.to_s.downcase.to_sym if param == :name and namevar param = namevar end param end # The namevar for our resource type. If the type doesn't exist, # always use :name. def namevar if builtin_type? && !(t = resource_type).nil? && t.key_attributes.length == 1 t.key_attributes.first else :name end end def extract_parameters(params) params.each do |param, value| validate_parameter(param) if strict? self[param] = value end end # Produces a hash with { :key => part_of_title } for each entry in title_patterns # for the resource type. A typical result for a title of 'example' is {:name => 'example'}. # A resource type with a complex title to attribute mapping returns one entry in the hash # per part. # def parse_title h = {} type = resource_type if type.respond_to?(:title_patterns) && !type.title_patterns.nil? type.title_patterns.each do |regexp, symbols_and_lambdas| captures = regexp.match(title.to_s) next unless captures symbols_and_lambdas.zip(captures[1..]).each do |symbol_and_lambda, capture| symbol, proc = symbol_and_lambda # Many types pass "identity" as the proc; we might as well give # them a shortcut to delivering that without the extra cost. # # Especially because the global type defines title_patterns and # uses the identity patterns. # # This was worth about 8MB of memory allocation saved in my # testing, so is worth the complexity for the API. if proc then h[symbol] = proc.call(capture) else h[symbol] = capture end end return h end # If we've gotten this far, then none of the provided title patterns # matched. Since there's no way to determine the title then the # resource should fail here. raise Puppet::Error, _("No set of title patterns matched the title \"%{title}\".") % { title: title } else { :name => title.to_s } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/trusted_external.rb
lib/puppet/trusted_external.rb
# frozen_string_literal: true # A method for retrieving external trusted facts module Puppet::TrustedExternal def retrieve(certname) command = Puppet[:trusted_external_command] return nil unless command Puppet.debug { _("Retrieving trusted external data from %{command}") % { command: command } } setting_type = Puppet.settings.setting(:trusted_external_command).type if setting_type == :file return fetch_data(command, certname) end # command is a directory. Thus, data is a hash of <basename> => <data> for # each executable file in command. For example, if the files 'servicenow.rb', # 'unicorn.sh' are in command, then data is the following hash: # { 'servicenow' => <servicenow.rb output>, 'unicorn' => <unicorn.sh output> } data = {} Puppet::FileSystem.children(command).each do |file| abs_path = Puppet::FileSystem.expand_path(file) executable_file = Puppet::FileSystem.file?(abs_path) && Puppet::FileSystem.executable?(abs_path) unless executable_file Puppet.debug { _("Skipping non-executable file %{file}") % { file: abs_path } } next end basename = file.basename(file.extname).to_s unless data[basename].nil? raise Puppet::Error, _("There is more than one '%{basename}' script in %{dir}") % { basename: basename, dir: command } end data[basename] = fetch_data(abs_path, certname) end data end module_function :retrieve def fetch_data(command, certname) result = Puppet::Util::Execution.execute([command, certname], { :combine => false, :failonfail => true, }) JSON.parse(result) end module_function :fetch_data end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_bucket.rb
lib/puppet/file_bucket.rb
# frozen_string_literal: true # stub module Puppet::FileBucket class BucketError < RuntimeError; end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/confine_collection.rb
lib/puppet/confine_collection.rb
# frozen_string_literal: true # Manage a collection of confines, returning a boolean or # helpful information. require_relative '../puppet/confine' class Puppet::ConfineCollection def confine(hash) if hash.include?(:for_binary) for_binary = true hash.delete(:for_binary) else for_binary = false end hash.each do |test, values| klass = Puppet::Confine.test(test) if klass @confines << klass.new(values) @confines[-1].for_binary = true if for_binary else confine = Puppet::Confine.test(:variable).new(values) confine.name = test @confines << confine end @confines[-1].label = label end end attr_reader :label def initialize(label) @label = label @confines = [] end # Return a hash of the whole confine set, used for the Provider # reference. def summary confines = Hash.new { |hash, key| hash[key] = [] } @confines.each { |confine| confines[confine.class] << confine } result = {} confines.each do |klass, list| value = klass.summarize(list) next if (value.respond_to?(:length) and value.length == 0) or (value == 0) result[klass.name] = value end result end def valid? !@confines.detect { |c| !c.valid? } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/vendor.rb
lib/puppet/vendor.rb
# frozen_string_literal: true module Puppet # Simple module to manage vendored code. # # To vendor a library: # # * Download its whole git repo or untar into `lib/puppet/vendor/<libname>` # * Create a vendor/puppetload_libraryname.rb file to add its libdir into the $:. # (Look at existing load_xxx files, they should all follow the same pattern). # * Add a <libname>/PUPPET_README.md file describing what the library is for # and where it comes from. # * To load the vendored lib upfront, add a `require '<vendorlib>'`line to # `vendor/require_vendored.rb`. # * To load the vendored lib on demand, add a comment to `vendor/require_vendored.rb` # to make it clear it should not be loaded upfront. # # At runtime, the #load_vendored method should be called. It will ensure # all vendored libraries are added to the global `$:` path, and # will then call execute the up-front loading specified in `vendor/require_vendored.rb`. # # The intention is to not change vendored libraries and to eventually # make adding them in optional so that distros can simply adjust their # packaging to exclude this directory and the various load_xxx.rb scripts # if they wish to install these gems as native packages. # class Vendor class << self # @api private def vendor_dir File.join([File.dirname(File.expand_path(__FILE__)), "vendor"]) end # @api private def load_entry(entry) Puppet.debug("Loading vendored #{entry}") load "#{vendor_dir}/#{entry}" end # @api private def require_libs require_relative 'vendor/require_vendored' end # Configures the path for all vendored libraries and loads required libraries. # (This is the entry point for loading vendored libraries). # def load_vendored Dir.entries(vendor_dir).each do |entry| if entry =~ /load_(\w+?)\.rb$/ load_entry entry end end require_libs end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/version.rb
lib/puppet/version.rb
# frozen_string_literal: true # 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 can be set programmatically because we want to allow the # Raketasks and such to set the version based on the output of `git describe` module Puppet PUPPETVERSION = '8.11.0' ## # 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" def self.version version_file = File.join(File.dirname(__FILE__), 'VERSION') return @puppet_version if @puppet_version @puppet_version = read_version_file(version_file) || PUPPETVERSION end # @return [String] containing the puppet version to minor specificity, e.g. "3.0" def self.minor_version version.split('.')[0..1].join('.') end def self.version=(version) @puppet_version = version end ## # read_version_file reads the content of the "VERSION" file that lives in the # same directory as this source code file. # # @api private # # @return [String] for example: "1.6.14-6-gea42046" or nil if the VERSION # file does not exist. def self.read_version_file(path) if File.exist?(path) File.read(path).chomp end end private_class_method :read_version_file end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application.rb
lib/puppet/application.rb
# frozen_string_literal: true require 'optparse' require_relative '../puppet/util/command_line' require_relative '../puppet/util/constant_inflector' require_relative '../puppet/error' require_relative '../puppet/application_support' module Puppet # Defines an abstract Puppet application. # # # Usage # # To create a new application extend `Puppet::Application`. Derived applications # must implement the `main` method and should implement the `summary` and # `help` methods in order to be included in `puppet help`, and should define # application-specific options. For example: # # ``` # class Puppet::Application::Example < Puppet::Application # # def summary # "My puppet example application" # end # # def help # <<~HELP # puppet-example(8) -- #{summary} # ... # HELP # end # # # define arg with a required option # option("--arg ARGUMENT") do |v| # options[:arg] = v # end # # # define arg with an optional option # option("--maybe [ARGUMENT]") do |v| # options[:maybe] = v # end # # # define long and short arg # option("--all", "-a") # # def initialize(command_line = Puppet::Util::CommandLine.new) # super # @data = {} # end # # def main # # call action # send(@command_line.args.shift) # end # # def read # # read action # end # # def write # # write action # end # # end # ``` # # Puppet defines the following application lifecycle methods that are called in # the following order: # # * {#initialize} # * {#initialize_app_defaults} # * {#preinit} # * {#parse_options} # * {#setup} # * {#main} # # ## Execution state # The class attributes/methods of Puppet::Application serve as a global place to set and query the execution # status of the application: stopping, restarting, etc. The setting of the application status does not directly # affect its running status; it's assumed that the various components within the application will consult these # settings appropriately and affect their own processing accordingly. Control operations (signal handlers and # the like) should set the status appropriately to indicate to the overall system that it's the process of # stopping or restarting (or just running as usual). # # So, if something in your application needs to stop the process, for some reason, you might consider: # # ``` # def stop_me! # # indicate that we're stopping # Puppet::Application.stop! # # ...do stuff... # end # ``` # # And, if you have some component that involves a long-running process, you might want to consider: # # ``` # def my_long_process(giant_list_to_munge) # giant_list_to_munge.collect do |member| # # bail if we're stopping # return if Puppet::Application.stop_requested? # process_member(member) # end # end # ``` # @abstract # @api public class Application require_relative '../puppet/util' include Puppet::Util DOCPATTERN = ::File.expand_path(::File.dirname(__FILE__) + "/util/command_line/*") CommandLineArgs = Struct.new(:subcommand_name, :args) @loader = Puppet::Util::Autoload.new(self, 'puppet/application') class << self include Puppet::Util attr_accessor :run_status def clear! self.run_status = nil end # Signal that the application should stop. # @api public def stop! self.run_status = :stop_requested end # Signal that the application should restart. # @api public def restart! self.run_status = :restart_requested end # Indicates that Puppet::Application.restart! has been invoked and components should # do what is necessary to facilitate a restart. # @api public def restart_requested? :restart_requested == run_status end # Indicates that Puppet::Application.stop! has been invoked and components should do what is necessary # for a clean stop. # @api public def stop_requested? :stop_requested == run_status end # Indicates that one of stop! or start! was invoked on Puppet::Application, and some kind of process # shutdown/short-circuit may be necessary. # @api public def interrupted? [:restart_requested, :stop_requested].include? run_status end # Indicates that Puppet::Application believes that it's in usual running run_mode (no stop/restart request # currently active). # @api public def clear? run_status.nil? end # Only executes the given block if the run status of Puppet::Application is clear (no restarts, stops, # etc. requested). # Upon block execution, checks the run status again; if a restart has been requested during the block's # execution, then controlled_run will send a new HUP signal to the current process. # Thus, long-running background processes can potentially finish their work before a restart. def controlled_run(&block) return unless clear? result = block.call Process.kill(:HUP, $PID) if restart_requested? result end # used to declare code that handle an option def option(*options, &block) long = options.find { |opt| opt =~ /^--/ }.gsub(/^--(?:\[no-\])?([^ =]+).*$/, '\1').tr('-', '_') fname = "handle_#{long}".intern if block_given? define_method(fname, &block) else define_method(fname) do |value| self.options[long.to_s.to_sym] = value end end option_parser_commands << [options, fname] end def banner(banner = nil) @banner ||= banner end def option_parser_commands @option_parser_commands ||= ( superclass.respond_to?(:option_parser_commands) ? superclass.option_parser_commands.dup : [] ) @option_parser_commands end # @return [Array<String>] the names of available applications # @api public def available_application_names # Use our configured environment to load the application, as it may # be in a module we installed locally, otherwise fallback to our # current environment (*root*). Once we load the application the # current environment will change from *root* to the application # specific environment. environment = Puppet.lookup(:environments).get(Puppet[:environment]) || Puppet.lookup(:current_environment) @loader.files_to_load(environment).map do |fn| ::File.basename(fn, '.rb') end.uniq end # Finds the class for a given application and loads the class. This does # not create an instance of the application, it only gets a handle to the # class. The code for the application is expected to live in a ruby file # `puppet/application/#{name}.rb` that is available on the `$LOAD_PATH`. # # @param application_name [String] the name of the application to find (eg. "apply"). # @return [Class] the Class instance of the application that was found. # @raise [Puppet::Error] if the application class was not found. # @raise [LoadError] if there was a problem loading the application file. # @api public def find(application_name) begin require @loader.expand(application_name.to_s.downcase) rescue LoadError => e Puppet.log_and_raise(e, _("Unable to find application '%{application_name}'. %{error}") % { application_name: application_name, error: e }) end class_name = Puppet::Util::ConstantInflector.file2constant(application_name.to_s) clazz = try_load_class(class_name) ################################################################ #### Begin 2.7.x backward compatibility hack; #### eventually we need to issue a deprecation warning here, #### and then get rid of this stanza in a subsequent release. ################################################################ if clazz.nil? class_name = application_name.capitalize clazz = try_load_class(class_name) end ################################################################ #### End 2.7.x backward compatibility hack ################################################################ if clazz.nil? raise Puppet::Error, _("Unable to load application class '%{class_name}' from file 'puppet/application/%{application_name}.rb'") % { class_name: class_name, application_name: application_name } end clazz end # Given the fully qualified name of a class, attempt to get the class instance. # @param [String] class_name the fully qualified name of the class to try to load # @return [Class] the Class instance, or nil? if it could not be loaded. def try_load_class(class_name) const_defined?(class_name) ? const_get(class_name) : nil end private :try_load_class # Return an instance of the specified application. # # @param [Symbol] name the lowercase name of the application # @return [Puppet::Application] an instance of the specified name # @raise [Puppet::Error] if the application class was not found. # @raise [LoadError] if there was a problem loading the application file. # @api public def [](name) find(name).new end # Sets or gets the run_mode name. Sets the run_mode name if a mode_name is # passed. Otherwise, gets the run_mode or a default run_mode # @api public def run_mode(mode_name = nil) if mode_name Puppet.settings.preferred_run_mode = mode_name end return @run_mode if @run_mode and !mode_name require_relative '../puppet/util/run_mode' @run_mode = Puppet::Util::RunMode[mode_name || Puppet.settings.preferred_run_mode] end # Sets environment_mode name. When acting as a compiler, the environment mode # should be `:local` since the directory must exist to compile the catalog. # When acting as an agent, the environment mode should be `:remote` since # the Puppet[:environment] setting refers to an environment directoy on a remote # system. The `:not_required` mode is for cases where the application does not # need an environment to run. # # @param mode_name [Symbol] The name of the environment mode to run in. May # be one of `:local`, `:remote`, or `:not_required`. This impacts where the # application looks for its specified environment. If `:not_required` or # `:remote` are set, the application will not fail if the environment does # not exist on the local filesystem. # @api public def environment_mode(mode_name) raise Puppet::Error, _("Invalid environment mode '%{mode_name}'") % { mode_name: mode_name } unless [:local, :remote, :not_required].include?(mode_name) @environment_mode = mode_name end # Gets environment_mode name. If none is set with `environment_mode=`, # default to :local. # @return [Symbol] The current environment mode # @api public def get_environment_mode @environment_mode || :local end # This is for testing only # @api public def clear_everything_for_tests @run_mode = @banner = @run_status = @option_parser_commands = nil end end attr_reader :options, :command_line # Every app responds to --version # See also `lib/puppet/util/command_line.rb` for some special case early # handling of this. option("--version", "-V") do |_arg| puts Puppet.version exit(0) end # Every app responds to --help option("--help", "-h") do |_v| puts help exit(0) end # Initialize the application receiving the {Puppet::Util::CommandLine} object # containing the application name and arguments. # # @param command_line [Puppet::Util::CommandLine] An instance of the command line to create the application with # @api public def initialize(command_line = Puppet::Util::CommandLine.new) @command_line = CommandLineArgs.new(command_line.subcommand_name, command_line.args.dup) @options = {} end # Now that the `run_mode` has been resolved, return default settings for the # application. Note these values may be overridden when puppet's configuration # is loaded later. # # @example To override the facts terminus: # def app_defaults # super.merge({ # :facts_terminus => 'yaml' # }) # end # # @return [Hash<String, String>] default application settings # @api public def app_defaults Puppet::Settings.app_defaults_for_run_mode(self.class.run_mode).merge( :name => name ) end # Initialize application defaults. It's usually not necessary to override this method. # @return [void] # @api public def initialize_app_defaults Puppet.settings.initialize_app_defaults(app_defaults) end # The preinit block is the first code to be called in your application, after # `initialize`, but before option parsing, setup or command execution. It is # usually not necessary to override this method. # @return [void] # @api public def preinit end # Call in setup of subclass to deprecate an application. # @return [void] # @api public def deprecate @deprecated = true end # Return true if this application is deprecated. # @api public def deprecated? @deprecated end # Execute the application. This method should not be overridden. # @return [void] # @api public def run # I don't really like the names of these lifecycle phases. It would be nice to change them to some more meaningful # names, and make deprecated aliases. --cprice 2012-03-16 exit_on_fail(_("Could not get application-specific default settings")) do initialize_app_defaults end Puppet::ApplicationSupport.push_application_context(self.class.run_mode, self.class.get_environment_mode) exit_on_fail(_("Could not initialize")) { preinit } exit_on_fail(_("Could not parse application options")) { parse_options } exit_on_fail(_("Could not prepare for execution")) { setup } if deprecated? Puppet.deprecation_warning(_("`puppet %{name}` is deprecated and will be removed in a future release.") % { name: name }) end exit_on_fail(_("Could not configure routes from %{route_file}") % { route_file: Puppet[:route_file] }) { configure_indirector_routes } exit_on_fail(_("Could not log runtime debug info")) { log_runtime_environment } exit_on_fail(_("Could not run")) { run_command } end # This method must be overridden and perform whatever action is required for # the application. The `command_line` reader contains the actions and # arguments. # @return [void] # @api public def main raise NotImplementedError, _("No valid command or main") end # Run the application. By default, it calls {#main}. # @return [void] # @api public def run_command main end # Setup the application. It is usually not necessary to override this method. # @return [void] # @api public def setup setup_logs end # Setup logging. By default the `console` log destination will only be created # if `debug` or `verbose` is specified on the command line. Override to customize # the logging behavior. # @return [void] # @api public def setup_logs handle_logdest_arg(Puppet[:logdest]) unless options[:setdest] unless options[:setdest] if options[:debug] || options[:verbose] Puppet::Util::Log.newdestination(:console) end end set_log_level Puppet::Util::Log.setup_default unless options[:setdest] end def set_log_level(opts = nil) opts ||= options if opts[:debug] Puppet::Util::Log.level = :debug elsif opts[:verbose] && !Puppet::Util::Log.sendlevel?(:info) Puppet::Util::Log.level = :info end end def handle_logdest_arg(arg) return if arg.nil? logdest = arg.split(',').map!(&:strip) Puppet[:logdest] = arg logdest.each do |dest| Puppet::Util::Log.newdestination(dest) options[:setdest] = true rescue => detail Puppet.log_and_raise(detail, _("Could not set logdest to %{dest}.") % { dest: arg }) end end def configure_indirector_routes Puppet::ApplicationSupport.configure_indirector_routes(name.to_s) end # Output basic information about the runtime environment for debugging # purposes. # # @param extra_info [Hash{String => #to_s}] a flat hash of extra information # to log. Intended to be passed to super by subclasses. # @return [void] # @api public def log_runtime_environment(extra_info = nil) runtime_info = { 'puppet_version' => Puppet.version, 'ruby_version' => RUBY_VERSION, 'run_mode' => self.class.run_mode.name } unless Puppet::Util::Platform.jruby_fips? runtime_info['openssl_version'] = "'#{OpenSSL::OPENSSL_VERSION}'" runtime_info['openssl_fips'] = OpenSSL::OPENSSL_FIPS end runtime_info['default_encoding'] = Encoding.default_external runtime_info.merge!(extra_info) unless extra_info.nil? Puppet.debug 'Runtime environment: ' + runtime_info.map { |k, v| k + '=' + v.to_s }.join(', ') end # Options defined with the `option` method are parsed from settings and the command line. # Refer to {OptionParser} documentation for the exact format. Options are parsed as follows: # # * If the option method is given a block, then it will be called whenever the option is encountered in the command-line argument. # * If the option method has no block, then the default option handler will store the argument in the `options` instance variable. # * If a given option was not defined by an `option` method, but it exists as a Puppet setting: # * if `unknown` was used with a block, it will be called with the option name and argument. # * if `unknown` wasn't used, then the option/argument is handed to Puppet.settings.handlearg for # a default behavior. # * The `-h` and `--help` options are automatically handled by the command line before creating the application. # # Options specified on the command line override settings. It is usually not # necessary to override this method. # @return [void] # @api public def parse_options # Create an option parser option_parser = OptionParser.new(self.class.banner) # Here we're building up all of the options that the application may need to handle. The main # puppet settings defined in "defaults.rb" have already been parsed once (in command_line.rb) by # the time we get here; however, our app may wish to handle some of them specially, so we need to # make the parser aware of them again. We might be able to make this a bit more efficient by # re-using the parser object that gets built up in command_line.rb. --cprice 2012-03-16 # Add all global options to it. Puppet.settings.optparse_addargs([]).each do |option| option_parser.on(*option) do |arg| handlearg(option[0], arg) end end # Add options that are local to this application, which were # created using the "option()" metaprogramming method. If there # are any conflicts, this application's options will be favored. self.class.option_parser_commands.each do |options, fname| option_parser.on(*options) do |value| # Call the method that "option()" created. send(fname, value) end end # Scan command line. We just hand any exceptions to our upper levels, # rather than printing help and exiting, so that we can meaningfully # respond with context-sensitive help if we want to. --daniel 2011-04-12 option_parser.parse!(command_line.args) end def handlearg(opt, val) opt, val = Puppet::Settings.clean_opt(opt, val) send(:handle_unknown, opt, val) if respond_to?(:handle_unknown) end # this is used for testing def self.exit(code) exit(code) end def name self.class.to_s.sub(/.*::/, "").downcase.to_sym end # Return the text to display when running `puppet help`. # @return [String] The help to display # @api public def help _("No help available for puppet %{app_name}") % { app_name: name } end # The description used in top level `puppet help` output # If left empty in implementations, we will attempt to extract # the summary from the help text itself. # @return [String] # @api public def summary "" end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/forge.rb
lib/puppet/forge.rb
# frozen_string_literal: true require_relative '../puppet/vendor' Puppet::Vendor.load_vendored require 'net/http' require 'tempfile' require 'uri' require 'pathname' require_relative '../puppet/util/json' require 'semantic_puppet' class Puppet::Forge < SemanticPuppet::Dependency::Source require_relative 'forge/cache' require_relative 'forge/repository' require_relative 'forge/errors' include Puppet::Forge::Errors USER_AGENT = "PMT/1.1.1 (v3; Net::HTTP)" # From https://forgeapi.puppet.com/#!/release/getReleases MODULE_RELEASE_EXCLUSIONS = %w[readme changelog license uri module tags supported file_size downloads created_at updated_at deleted_at].join(',').freeze attr_reader :host, :repository def initialize(host = Puppet[:module_repository]) @host = host @repository = Puppet::Forge::Repository.new(host, USER_AGENT) end # Return a list of module metadata hashes that match the search query. # This return value is used by the module_tool face install search, # and displayed to on the console. # # Example return value: # # [ # { # "author" => "puppetlabs", # "name" => "bacula", # "tag_list" => ["backup", "bacula"], # "releases" => [{"version"=>"0.0.1"}, {"version"=>"0.0.2"}], # "full_name" => "puppetlabs/bacula", # "version" => "0.0.2", # "project_url" => "https://github.com/puppetlabs/puppetlabs-bacula", # "desc" => "bacula" # } # ] # # @param term [String] search term # @return [Array] modules found # @raise [Puppet::Forge::Errors::CommunicationError] if there is a network # related error # @raise [Puppet::Forge::Errors::SSLVerifyError] if there is a problem # verifying the remote SSL certificate # @raise [Puppet::Forge::Errors::ResponseError] if the repository returns a # bad HTTP response def search(term) matches = [] uri = "/v3/modules?query=#{term}" if Puppet[:module_groups] uri += "&module_groups=#{Puppet[:module_groups].tr('+', ' ')}" end while uri # make_http_request URI encodes parameters response = make_http_request(uri) if response.code == 200 result = Puppet::Util::Json.load(response.body) uri = decode_uri(result['pagination']['next']) matches.concat result['results'] else raise ResponseError.new(:uri => response.url, :response => response) end end matches.each do |mod| mod['author'] = mod['owner']['username'] mod['tag_list'] = mod['current_release']['tags'] mod['full_name'] = "#{mod['author']}/#{mod['name']}" mod['version'] = mod['current_release']['version'] mod['project_url'] = mod['homepage_url'] mod['desc'] = mod['current_release']['metadata']['summary'] || '' end end # Fetches {ModuleRelease} entries for each release of the named module. # # @param input [String] the module name to look up # @return [Array<SemanticPuppet::Dependency::ModuleRelease>] a list of releases for # the given name # @see SemanticPuppet::Dependency::Source#fetch def fetch(input) name = input.tr('/', '-') uri = "/v3/releases?module=#{name}&sort_by=version&exclude_fields=#{MODULE_RELEASE_EXCLUSIONS}" if Puppet[:module_groups] uri += "&module_groups=#{Puppet[:module_groups].tr('+', ' ')}" end releases = [] while uri # make_http_request URI encodes parameters response = make_http_request(uri) if response.code == 200 response = Puppet::Util::Json.load(response.body) else raise ResponseError.new(:uri => response.url, :response => response) end releases.concat(process(response['results'])) uri = decode_uri(response['pagination']['next']) end releases end def make_http_request(*args) @repository.make_http_request(*args) end class ModuleRelease < SemanticPuppet::Dependency::ModuleRelease attr_reader :install_dir, :metadata def initialize(source, data) @data = data @metadata = meta = data['metadata'] name = meta['name'].tr('/', '-') version = SemanticPuppet::Version.parse(meta['version']) release = "#{name}@#{version}" if meta['dependencies'] dependencies = meta['dependencies'].collect do |dep| Puppet::ModuleTool::Metadata.new.add_dependency(dep['name'], dep['version_requirement'], dep['repository']) Puppet::ModuleTool.parse_module_dependency(release, dep)[0..1] rescue ArgumentError => e raise ArgumentError, _("Malformed dependency: %{name}.") % { name: dep['name'] } + ' ' + _("Exception was: %{detail}") % { detail: e } end else dependencies = [] end super(source, name, version, dependencies.to_h) end def install(dir) staging_dir = prepare module_dir = dir + name[/-(.*)/, 1] module_dir.rmtree if module_dir.exist? # Make sure unpacked module has the same ownership as the folder we are moving it into. Puppet::ModuleTool::Applications::Unpacker.harmonize_ownership(dir, staging_dir) FileUtils.mv(staging_dir, module_dir) @install_dir = dir # Return the Pathname object representing the directory where the # module release archive was unpacked the to. module_dir ensure staging_dir.rmtree if staging_dir.exist? end def prepare return @unpacked_into if @unpacked_into Puppet.warning "#{@metadata['name']} has been deprecated by its author! View module on Puppet Forge for more info." if deprecated? download(@data['file_uri'], tmpfile) checksum = @data['file_sha256'] if checksum validate_checksum(tmpfile, checksum, Digest::SHA256) else checksum = @data['file_md5'] if checksum validate_checksum(tmpfile, checksum, Digest::MD5) else raise _("Forge module is missing SHA256 and MD5 checksums") end end unpack(tmpfile, tmpdir) @unpacked_into = Pathname.new(tmpdir) end private # Obtain a suitable temporary path for unpacking tarballs # # @return [Pathname] path to temporary unpacking location # rubocop:disable Naming/MemoizedInstanceVariableName def tmpdir @dir ||= Dir.mktmpdir(name, Puppet::Forge::Cache.base_path) end def tmpfile @file ||= Tempfile.new(name, Puppet::Forge::Cache.base_path).tap(&:binmode) end # rubocop:enable Naming/MemoizedInstanceVariableName def download(uri, destination) response = @source.make_http_request(uri, destination) destination.flush and destination.close unless response.code == 200 raise Puppet::Forge::Errors::ResponseError.new(:uri => response.url, :response => response) end end def validate_checksum(file, checksum, digest_class) if Puppet.runtime[:facter].value(:fips_enabled) && digest_class == Digest::MD5 raise _("Module install using MD5 is prohibited in FIPS mode.") end if digest_class.file(file.path).hexdigest != checksum raise RuntimeError, _("Downloaded release for %{name} did not match expected checksum %{checksum}") % { name: name, checksum: checksum } end end def unpack(file, destination) Puppet::ModuleTool::Applications::Unpacker.unpack(file.path, destination) rescue Puppet::ExecutionFailure => e raise RuntimeError, _("Could not extract contents of module archive: %{message}") % { message: e.message } end def deprecated? @data['module'] && !@data['module']['deprecated_at'].nil? end end private def process(list) l = list.map do |release| metadata = release['metadata'] begin ModuleRelease.new(self, release) rescue ArgumentError => e Puppet.warning _("Cannot consider release %{name}-%{version}: %{error}") % { name: metadata['name'], version: metadata['version'], error: e } false end end l.select { |r| r } end def decode_uri(uri) return if uri.nil? Puppet::Util.uri_unescape(uri.tr('+', ' ')) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/datatypes.rb
lib/puppet/datatypes.rb
# frozen_string_literal: true # Data types in the Puppet Language can have implementations written in Ruby # and distributed in puppet modules. A data type can be declared together with # its implementation by creating a file in 'lib/puppet/functions/<modulename>'. # The name of the file must be the downcased name of the data type followed by # the extension '.rb'. # # A data type is created by calling {Puppet::DataTypes.create_type(<type name>)} # and passing it a block that defines the data type interface and implementation. # # Data types are namespaced inside the modules that contains them. The name of the # data type is prefixed with the name of the module. As with all type names, each # segment of the name must start with an uppercase letter. # # @example A simple data type # Puppet::DataTypes.create_type('Auth::User') do # interface <<-PUPPET # attributes => { # name => String, # email => String # } # PUPPET # end # # The above example does not declare an implementation which makes it equivalent # to adding the following contents in a file named 'user.pp' under the 'types' directory # of the module root. # # type Auth::User = Object[ # attributes => { # name => String, # email => String # }] # # Both declarations are valid and will be found by the module loader. # # Structure of a data type # --- # # A Data Type consists of an interface and an implementation. Unless a registered implementation # is found, the type system will automatically generate one. An automatically generated # implementation is all that is needed when the interface fully defines the behaviour (for # example in the common case when the data type has no other behaviour than having attributes). # # When the automatically generated implementation is not sufficient, one must be implemented and # registered. The implementation can either be done next to the interface definition by passing # a block to `implementation`, or map to an existing implementation class by passing the class # as an argument to `implementation_class`. An implementation class does not have to be special # in other respects than that it must implemented the type's interface. This makes it possible # to use existing Ruby data types as data types in the puppet language. # # Note that when using `implementation_class` there can only be one such implementation across # all environments managed by one puppet server and you must handle and install these # implementations as if they are part of the puppet platform. In contrast; the type # implementations that are done inside of the type's definition are safe to use in different # versions in different environments (given that they do not need additional external logic to # be loaded). # # When using an `implementation_class` it is sometimes desirable to load this class from the # 'lib' directory of the module. The method `load_file` is provided to facilitate such a load. # The `load_file` will use the `Puppet::Util::Autoload` to search for the given file in the 'lib' # directory of the current environment and the 'lib' directory in each included module. # # @example Adding implementation on top of the generated type using `implementation` # Puppet::DataTypes.create_type('Auth::User') do # interface <<-PUPPET # attributes => { # name => String, # email => String, # year_of_birth => Integer, # age => { type => Integer, kind => derived } # } # PUPPET # # implementation do # def age # DateTime.now.year - @year_of_birth # end # end # end # # @example Appointing an already existing implementation class # # Assumes the following class is declared under 'lib/puppetx/auth' in the module: # # class PuppetX::Auth::User # attr_reader :name, :year_of_birth # def initialize(name, year_of_birth) # @name = name # @year_of_birth = year_of_birth # end # # def age # DateTime.now.year - @year_of_birth # end # # def send_text(sender, text) # sender.send_text_from(@name, text) # end # end # # Then the type declaration can look like this: # # Puppet::DataTypes.create_type('Auth::User') do # interface <<-PUPPET # attributes => { # name => String, # email => String, # year_of_birth => Integer, # age => { type => Integer, kind => derived } # }, # functions => { # send_text => Callable[Sender, String[1]] # } # PUPPET # # # This load_file is optional and only needed in case # # the implementation is not loaded by other means. # load_file 'puppetx/auth/user' # # implementation_class PuppetX::Auth::User # end # module Puppet::DataTypes def self.create_type(type_name, &block) # Ruby < 2.1.0 does not have method on Binding, can only do eval # and it will fail unless protected with an if defined? if the local # variable does not exist in the block's binder. # loader = block.binding.eval('loader_injected_arg if defined?(loader_injected_arg)') create_loaded_type(type_name, loader, &block) rescue StandardError => e raise ArgumentError, _("Data Type Load Error for type '%{type_name}': %{message}") % { type_name: type_name, message: e.message } end def self.create_loaded_type(type_name, loader, &block) builder = TypeBuilder.new(type_name.to_s) api = TypeBuilderAPI.new(builder).freeze api.instance_eval(&block) builder.create_type(loader) end # @api private class TypeBuilder attr_accessor :interface, :implementation, :implementation_class def initialize(type_name) @type_name = type_name @implementation = nil @implementation_class = nil end def create_type(loader) raise ArgumentError, _('a data type must have an interface') unless @interface.is_a?(String) created_type = Puppet::Pops::Types::PObjectType.new( @type_name, Puppet::Pops::Parser::EvaluatingParser.new.parse_string("{ #{@interface} }").body ) if !@implementation_class.nil? if @implementation_class < Puppet::Pops::Types::PuppetObject @implementation_class.instance_eval do include Puppet::Pops::Types::PuppetObject @_pcore_type = created_type def self._pcore_type @_pcore_type end end else Puppet::Pops::Loaders.implementation_registry.register_implementation(created_type, @implementation_class) end created_type.implementation_class = @implementation_class elsif !@implementation.nil? created_type.implementation_override = @implementation end created_type end def has_implementation? !(@implementation_class.nil? && @implementation.nil?) end end # The TypeBuilderAPI class exposes only those methods that the builder API provides # @api public class TypeBuilderAPI # @api private def initialize(type_builder) @type_builder = type_builder end def interface(type_string) raise ArgumentError, _('a data type can only have one interface') unless @type_builder.interface.nil? @type_builder.interface = type_string end def implementation(&block) raise ArgumentError, _('a data type can only have one implementation') if @type_builder.has_implementation? @type_builder.implementation = block end def implementation_class(ruby_class) raise ArgumentError, _('a data type can only have one implementation') if @type_builder.has_implementation? @type_builder.implementation_class = ruby_class end def load_file(file_name) Puppet::Util::Autoload.load_file(file_name, Puppet.lookup(:current_environment)) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/daemon.rb
lib/puppet/daemon.rb
# frozen_string_literal: true require_relative '../puppet/application' require_relative '../puppet/scheduler' # Run periodic actions in a daemonized process. # # A Daemon has 2 parts: # * config reparse # * an agent that responds to #run # # The config reparse will occur periodically based on Settings. The agent # is run periodically and a time interval based on Settings. The config # reparse will update this time interval when needed. # # The Daemon is also responsible for signal handling, starting, stopping, # running the agent on demand, and reloading the entire process. It ensures # that only one Daemon is running by using a lockfile. # # @api private class Puppet::Daemon SIGNAL_CHECK_INTERVAL = 5 attr_accessor :argv attr_reader :signals, :agent def initialize(agent, pidfile, scheduler = Puppet::Scheduler::Scheduler.new()) raise Puppet::DevError, _("Daemons must have an agent") unless agent @scheduler = scheduler @pidfile = pidfile @agent = agent @signals = [] end def daemonname Puppet.run_mode.name end # Put the daemon into the background. def daemonize pid = fork if pid Process.detach(pid) exit(0) end create_pidfile # Get rid of console logging Puppet::Util::Log.close(:console) Process.setsid Dir.chdir("/") close_streams end # Close stdin/stdout/stderr so that we can finish our transition into 'daemon' mode. # @return nil def self.close_streams Puppet.debug("Closing streams for daemon mode") begin $stdin.reopen "/dev/null" $stdout.reopen "/dev/null", "a" $stderr.reopen $stdout Puppet::Util::Log.reopen Puppet.debug("Finished closing streams for daemon mode") rescue => detail Puppet.err "Could not start #{Puppet.run_mode.name}: #{detail}" Puppet::Util.replace_file("/tmp/daemonout", 0o644) do |f| f.puts "Could not start #{Puppet.run_mode.name}: #{detail}" end exit(12) end end # Convenience signature for calling Puppet::Daemon.close_streams def close_streams Puppet::Daemon.close_streams end def reexec raise Puppet::DevError, _("Cannot reexec unless ARGV arguments are set") unless argv command = $PROGRAM_NAME + " " + argv.join(" ") Puppet.notice "Restarting with '#{command}'" stop(:exit => false) exec(command) end def reload agent.run({ :splay => false }) rescue Puppet::LockError Puppet.notice "Not triggering already-running agent" end def restart Puppet::Application.restart! reexec end def reopen_logs Puppet::Util::Log.reopen end # Trap a couple of the main signals. This should probably be handled # in a way that anyone else can register callbacks for traps, but, eh. def set_signal_traps [:INT, :TERM].each do |signal| Signal.trap(signal) do Puppet.notice "Caught #{signal}; exiting" stop end end # extended signals not supported under windows unless Puppet::Util::Platform.windows? signals = { :HUP => :restart, :USR1 => :reload, :USR2 => :reopen_logs } signals.each do |signal, method| Signal.trap(signal) do Puppet.notice "Caught #{signal}; storing #{method}" @signals << method end end end end # Stop everything def stop(args = { :exit => true }) Puppet::Application.stop! remove_pidfile Puppet::Util::Log.close_all exit if args[:exit] end def start create_pidfile run_event_loop end private # Create a pidfile for our daemon, so we can be stopped and others # don't try to start. def create_pidfile raise "Could not create PID file: #{@pidfile.file_path}" unless @pidfile.lock end # Remove the pid file for our daemon. def remove_pidfile @pidfile.unlock end # Loop forever running events - or, at least, until we exit. def run_event_loop splaylimit = Puppet[:splay] ? Puppet[:splaylimit] : 0 agent_run = Puppet::Scheduler.create_job(Puppet[:runinterval], true, splaylimit) do |job| if job.splay != 0 Puppet.info "Running agent every #{job.run_interval} seconds with splay #{job.splay} of #{job.splay_limit} seconds" else Puppet.info "Running agent every #{job.run_interval} seconds" end # Splay for the daemon is handled in the scheduler agent.run(:splay => false) end reparse_run = Puppet::Scheduler.create_job(Puppet[:filetimeout]) do Puppet.settings.reparse_config_files agent_run.run_interval = Puppet[:runinterval] # Puppet[:splaylimit] defaults to Puppet[:runinterval] so if runinterval # changes, but splaylimit doesn't, we'll still recalculate splay agent_run.splay_limit = Puppet[:splay] ? Puppet[:splaylimit] : 0 if Puppet[:filetimeout] == 0 reparse_run.disable else reparse_run.run_interval = Puppet[:filetimeout] end end signal_loop = Puppet::Scheduler.create_job(SIGNAL_CHECK_INTERVAL) do while method = @signals.shift # rubocop:disable Lint/AssignmentInCondition Puppet.notice "Processing #{method}" send(method) end end reparse_run.disable if Puppet[:filetimeout] == 0 # these are added in a different order than they are defined @scheduler.run_loop([reparse_run, agent_run, signal_loop]) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type.rb
lib/puppet/type.rb
# -*- coding: utf-8 -*- # frozen_string_literal: true require_relative '../puppet' require_relative '../puppet/util/log' require_relative '../puppet/util/metric' require_relative '../puppet/property' require_relative '../puppet/parameter' require_relative '../puppet/util' require_relative '../puppet/util/autoload' require_relative '../puppet/metatype/manager' require_relative '../puppet/util/errors' require_relative '../puppet/util/logging' require_relative '../puppet/util/tagging' require_relative '../puppet/concurrent/lock' # see the bottom of the file for the rest of the inclusions module Puppet # The base class for all Puppet types. # # A type describes: #-- # * **Attributes** - properties, parameters, and meta-parameters are different types of attributes of a type. # * **Properties** - these are the properties of the managed resource (attributes of the entity being managed; like # a file's owner, group and mode). A property describes two states; the 'is' (current state) and the 'should' (wanted # state). # * **Ensurable** - a set of traits that control the lifecycle (create, remove, etc.) of a managed entity. # There is a default set of operations associated with being _ensurable_, but this can be changed. # * **Name/Identity** - one property is the name/identity of a resource, the _namevar_ that uniquely identifies # one instance of a type from all others. # * **Parameters** - additional attributes of the type (that does not directly related to an instance of the managed # resource; if an operation is recursive or not, where to look for things, etc.). A Parameter (in contrast to Property) # has one current value where a Property has two (current-state and wanted-state). # * **Meta-Parameters** - parameters that are available across all types. A meta-parameter typically has # additional semantics; like the `require` meta-parameter. A new type typically does not add new meta-parameters, # but you need to be aware of their existence so you do not inadvertently shadow an existing meta-parameters. # * **Parent** - a type can have a super type (that it inherits from). # * **Validation** - If not just a basic data type, or an enumeration of symbolic values, it is possible to provide # validation logic for a type, properties and parameters. # * **Munging** - munging/unmunging is the process of turning a value in external representation (as used # by a provider) into an internal representation and vice versa. A Type supports adding custom logic for these. # * **Auto Requirements** - a type can specify automatic relationships to resources to ensure that if they are being # managed, they will be processed before this type. # * **Providers** - a provider is an implementation of a type's behavior - the management of a resource in the # system being managed. A provider is often platform specific and is selected at runtime based on # criteria/predicates specified in the configured providers. See {Puppet::Provider} for details. # * **Device Support** - A type has some support for being applied to a device; i.e. something that is managed # by running logic external to the device itself. There are several methods that deals with type # applicability for these special cases such as {apply_to_device}. # # Additional Concepts: # -- # * **Resource-type** - A _resource type_ is a term used to denote the type of a resource; internally a resource # is really an instance of a Ruby class i.e. {Puppet::Resource} which defines its behavior as "resource data". # Conceptually however, a resource is an instance of a subclass of Type (e.g. File), where such a class describes # its interface (what can be said/what is known about a resource of this type), # * **Managed Entity** - This is not a term in general use, but is used here when there is a need to make # a distinction between a resource (a description of what/how something should be managed), and what it is # managing (a file in the file system). The term _managed entity_ is a reference to the "file in the file system" # * **Isomorphism** - the quality of being _isomorphic_ means that two resource instances with the same name # refers to the same managed entity. Or put differently; _an isomorphic name is the identity of a resource_. # As an example, `exec` resources (that executes some command) have the command (i.e. the command line string) as # their name, and these resources are said to be non-isomorphic. # # @note The Type class deals with multiple concerns; some methods provide an internal DSL for convenient definition # of types, other methods deal with various aspects while running; wiring up a resource (expressed in Puppet DSL) # with its _resource type_ (i.e. an instance of Type) to enable validation, transformation of values # (munge/unmunge), etc. Lastly, Type is also responsible for dealing with Providers; the concrete implementations # of the behavior that constitutes how a particular Type behaves on a particular type of system (e.g. how # commands are executed on a flavor of Linux, on Windows, etc.). This means that as you are reading through the # documentation of this class, you will be switching between these concepts, as well as switching between # the conceptual level "a resource is an instance of a resource-type" and the actual implementation classes # (Type, Resource, Provider, and various utility and helper classes). # # @api public # # class Type extend Puppet::CompilableResourceType include Puppet::Util include Puppet::Util::Errors include Puppet::Util::Logging include Puppet::Util::Tagging # Comparing type instances. include Comparable # These variables are used in Metatype::Manager for managing types @types = {} @manager_lock = Puppet::Concurrent::Lock.new extend Puppet::MetaType::Manager # Compares this type against the given _other_ (type) and returns -1, 0, or +1 depending on the order. # @param other [Object] the object to compare against (produces nil, if not kind of Type} # @return [-1, 0, +1, nil] produces -1 if this type is before the given _other_ type, 0 if equals, and 1 if after. # Returns nil, if the given _other_ is not a kind of Type. # @see Comparable # def <=>(other) # Order is only maintained against other types, not arbitrary objects. # The natural order is based on the reference name used when comparing return nil unless other.is_a?(Puppet::CompilableResourceType) || other.class.is_a?(Puppet::CompilableResourceType) # against other type instances. ref <=> other.ref end # Code related to resource type attributes. class << self include Puppet::Util::ClassGen include Puppet::Util::Warnings # @return [Array<Puppet::Property>] The list of declared properties for the resource type. # The returned lists contains instances if Puppet::Property or its subclasses. attr_reader :properties end # Returns all the attribute names of the type in the appropriate order. # The {key_attributes} come first, then the {provider}, then the {properties}, and finally # the {parameters} and {metaparams}, # all in the order they were specified in the respective files. # @return [Array<String>] all type attribute names in a defined order. # def self.allattrs key_attributes | (parameters & [:provider]) | properties.collect(&:name) | parameters | metaparams end # Returns the class associated with the given attribute name. # @param name [String] the name of the attribute to obtain the class for # @return [Class, nil] the class for the given attribute, or nil if the name does not refer to an existing attribute # def self.attrclass(name) @attrclasses ||= {} # We cache the value, since this method gets called such a huge number # of times (as in, hundreds of thousands in a given run). unless @attrclasses.include?(name) @attrclasses[name] = case attrtype(name) when :property; @validproperties[name] when :meta; @@metaparamhash[name] when :param; @paramhash[name] end end @attrclasses[name] end # Returns the attribute type (`:property`, `;param`, `:meta`). # @comment What type of parameter are we dealing with? Cache the results, because # this method gets called so many times. # @return [Symbol] a symbol describing the type of attribute (`:property`, `;param`, `:meta`) # def self.attrtype(attr) @attrtypes ||= {} unless @attrtypes.include?(attr) @attrtypes[attr] = case when @validproperties.include?(attr); :property when @paramhash.include?(attr); :param when @@metaparamhash.include?(attr); :meta end end @attrtypes[attr] end # Provides iteration over meta-parameters. # @yieldparam p [Puppet::Parameter] each meta parameter # @return [void] # def self.eachmetaparam @@metaparams.each { |p| yield p.name } end # Creates a new `ensure` property with configured default values or with configuration by an optional block. # This method is a convenience method for creating a property `ensure` with default accepted values. # If no block is specified, the new `ensure` property will accept the default symbolic # values `:present`, and `:absent` - see {Puppet::Property::Ensure}. # If something else is wanted, pass a block and make calls to {Puppet::Property.newvalue} from this block # to define each possible value. If a block is passed, the defaults are not automatically added to the set of # valid values. # # @note This method will be automatically called without a block if the type implements the methods # specified by {ensurable?}. It is recommended to always call this method and not rely on this automatic # specification to clearly state that the type is ensurable. # # @overload ensurable() # @overload ensurable({ ... }) # @yield [ ] A block evaluated in scope of the new Parameter # @yieldreturn [void] # @return [void] # @dsl type # @api public # def self.ensurable(&block) if block_given? newproperty(:ensure, :parent => Puppet::Property::Ensure, &block) else newproperty(:ensure, :parent => Puppet::Property::Ensure) do defaultvalues end end end # Returns true if the type implements the default behavior expected by being _ensurable_ "by default". # A type is _ensurable_ by default if it responds to `:exists`, `:create`, and `:destroy`. # If a type implements these methods and have not already specified that it is _ensurable_, it will be # made so with the defaults specified in {ensurable}. # @return [Boolean] whether the type is _ensurable_ or not. # def self.ensurable? # If the class has all three of these methods defined, then it's # ensurable. [:exists?, :create, :destroy].all? { |method| public_method_defined?(method) } end # @comment These `apply_to` methods are horrible. They should really be implemented # as part of the usual system of constraints that apply to a type and # provider pair, but were implemented as a separate shadow system. # # @comment We should rip them out in favour of a real constraint pattern around the # target device - whatever that looks like - and not have this additional # magic here. --daniel 2012-03-08 # # Makes this type applicable to `:device`. # @return [Symbol] Returns `:device` # @api private # def self.apply_to_device @apply_to = :device end # Makes this type applicable to `:host`. # @return [Symbol] Returns `:host` # @api private # def self.apply_to_host @apply_to = :host end # Makes this type applicable to `:both` (i.e. `:host` and `:device`). # @return [Symbol] Returns `:both` # @api private # def self.apply_to_all @apply_to = :both end # Makes this type apply to `:host` if not already applied to something else. # @return [Symbol] a `:device`, `:host`, or `:both` enumeration # @api private def self.apply_to @apply_to ||= :host end # Returns true if this type is applicable to the given target. # @param target [Symbol] should be :device, :host or :target, if anything else, :host is enforced # @return [Boolean] true # @api private # def self.can_apply_to(target) [target == :device ? :device : :host, :both].include?(apply_to) end # Processes the options for a named parameter. # @param name [String] the name of a parameter # @param options [Hash] a hash of options # @option options [Boolean] :boolean if option set to true, an access method on the form _name_? is added for the param # @return [void] # def self.handle_param_options(name, options) # If it's a boolean parameter, create a method to test the value easily if options[:boolean] define_method(name.to_s + "?") do val = self[name] if val == :true or val == true true end end end end # Is the given parameter a meta-parameter? # @return [Boolean] true if the given parameter is a meta-parameter. # def self.metaparam?(param) @@metaparamhash.include?(param.intern) end # Returns the meta-parameter class associated with the given meta-parameter name. # Accepts a `nil` name, and return nil. # @param name [String, nil] the name of a meta-parameter # @return [Class,nil] the class for the given meta-parameter, or `nil` if no such meta-parameter exists, (or if # the given meta-parameter name is `nil`. # def self.metaparamclass(name) return nil if name.nil? @@metaparamhash[name.intern] end # Returns all meta-parameter names. # @return [Array<String>] all meta-parameter names # def self.metaparams @@metaparams.collect(&:name) end # Returns the documentation for a given meta-parameter of this type. # @param metaparam [Puppet::Parameter] the meta-parameter to get documentation for. # @return [String] the documentation associated with the given meta-parameter, or nil of no such documentation # exists. # @raise if the given metaparam is not a meta-parameter in this type # def self.metaparamdoc(metaparam) @@metaparamhash[metaparam].doc end # Creates a new meta-parameter. # This creates a new meta-parameter that is added to this and all inheriting types. # @param name [Symbol] the name of the parameter # @param options [Hash] a hash with options. # @option options [Class<inherits Puppet::Parameter>] :parent (Puppet::Parameter) the super class of this parameter # @option options [Hash{String => Object}] :attributes a hash that is applied to the generated class # by calling setter methods corresponding to this hash's keys/value pairs. This is done before the given # block is evaluated. # @option options [Boolean] :boolean (false) specifies if this is a boolean parameter # @option options [Boolean] :namevar (false) specifies if this parameter is the namevar # @option options [Symbol, Array<Symbol>] :required_features specifies required provider features by name # @return [Class<inherits Puppet::Parameter>] the created parameter # @yield [ ] a required block that is evaluated in the scope of the new meta-parameter # @api public # @dsl type # @todo Verify that this description is ok # def self.newmetaparam(name, options = {}, &block) @@metaparams ||= [] @@metaparamhash ||= {} name = name.intern param = genclass( name, :parent => options[:parent] || Puppet::Parameter, :prefix => "MetaParam", :hash => @@metaparamhash, :array => @@metaparams, :attributes => options[:attributes], &block ) # Grr. param.required_features = options[:required_features] if options[:required_features] handle_param_options(name, options) param.metaparam = true param end # Copies all of a resource's metaparameters (except `alias`) to a generated child resource # @param parameters [Hash] of a resource's parameters # @return [Void] def copy_metaparams(parameters) parameters.each do |name, param| self[name] = param.value if param.metaparam? && name != :alias end nil end # Returns the list of parameters that comprise the composite key / "uniqueness key". # All parameters that return true from #isnamevar? or is named `:name` are included in the returned result. # @see uniqueness_key # @return [Array<Puppet::Parameter>] WARNING: this return type is uncertain def self.key_attribute_parameters @key_attribute_parameters ||= ( @parameters.find_all { |param| param.isnamevar? or param.name == :name } ) end # Returns cached {key_attribute_parameters} names. # Key attributes are properties and parameters that comprise a composite key # or "uniqueness key". # @return [Array<String>] cached key_attribute names # def self.key_attributes # This is a cache miss around 0.05 percent of the time. --daniel 2012-07-17 # rubocop:disable Naming/MemoizedInstanceVariableName @key_attributes_cache ||= key_attribute_parameters.collect(&:name) # rubocop:enable Naming/MemoizedInstanceVariableName end # Returns any parameters that should be included by default in puppet resource's output # @return [Array<Symbol>] the parameters to include def self.parameters_to_include [] end # Returns a mapping from the title string to setting of attribute values. # This default implementation provides a mapping of title to the one and only _namevar_ present # in the type's definition. # @note Advanced: some logic requires this mapping to be done differently, using a different # validation/pattern, breaking up the title # into several parts assigning each to an individual attribute, or even use a composite identity where # all namevars are seen as part of the unique identity (such computation is done by the {#uniqueness} method. # These advanced options are rarely used (only one of the built in puppet types use this, and then only # a small part of the available functionality), and the support for these advanced mappings is not # implemented in a straight forward way. For these reasons, this method has been marked as private). # # @raise [Puppet::DevError] if there is no title pattern and there are two or more key attributes # @return [Array<Array<Regexp, Array<Array <Symbol, Proc>>>>, nil] a structure with a regexp and the first key_attribute ??? # @comment This wonderful piece of logic creates a structure used by Resource.parse_title which # has the capability to assign parts of the title to one or more attributes; It looks like an implementation # of a composite identity key (all parts of the key_attributes array are in the key). This can also # be seen in the method uniqueness_key. # The implementation in this method simply assigns the title to the one and only namevar (which is name # or a variable marked as namevar). # If there are multiple namevars (any in addition to :name?) then this method MUST be implemented # as it raises an exception if there is more than 1. Note that in puppet, it is only File that uses this # to create a different pattern for assigning to the :path attribute # This requires further digging. # The entire construct is somewhat strange, since resource checks if the method "title_patterns" is # implemented (it seems it always is) - why take this more expensive regexp mathching route for all # other types? # @api private # def self.title_patterns case key_attributes.length when 0; [] when 1; [[/(.*)/m, [[key_attributes.first]]]] else raise Puppet::DevError, _("you must specify title patterns when there are two or more key attributes") end end # Produces a resource's _uniqueness_key_ (or composite key). # This key is an array of all key attributes' values. Each distinct tuple must be unique for each resource type. # @see key_attributes # @return [Object] an object that is a _uniqueness_key_ for this object # def uniqueness_key self.class.key_attributes.sort_by(&:to_s).map { |attribute_name| self[attribute_name] } end # Creates a new parameter. # @param name [Symbol] the name of the parameter # @param options [Hash] a hash with options. # @option options [Class<inherits Puppet::Parameter>] :parent (Puppet::Parameter) the super class of this parameter # @option options [Hash{String => Object}] :attributes a hash that is applied to the generated class # by calling setter methods corresponding to this hash's keys/value pairs. This is done before the given # block is evaluated. # @option options [Boolean] :boolean (false) specifies if this is a boolean parameter # @option options [Boolean] :namevar (false) specifies if this parameter is the namevar # @option options [Symbol, Array<Symbol>] :required_features specifies required provider features by name # @return [Class<inherits Puppet::Parameter>] the created parameter # @yield [ ] a required block that is evaluated in the scope of the new parameter # @api public # @dsl type # def self.newparam(name, options = {}, &block) options[:attributes] ||= {} param = genclass( name, :parent => options[:parent] || Puppet::Parameter, :attributes => options[:attributes], :block => block, :prefix => "Parameter", :array => @parameters, :hash => @paramhash ) handle_param_options(name, options) # Grr. param.required_features = options[:required_features] if options[:required_features] param.isnamevar if options[:namevar] param end # Creates a new property. # @param name [Symbol] the name of the property # @param options [Hash] a hash with options. # @option options [Symbol] :array_matching (:first) specifies how the current state is matched against # the wanted state. Use `:first` if the property is single valued, and (`:all`) otherwise. # @option options [Class<inherits Puppet::Property>] :parent (Puppet::Property) the super class of this property # @option options [Hash{String => Object}] :attributes a hash that is applied to the generated class # by calling setter methods corresponding to this hash's keys/value pairs. This is done before the given # block is evaluated. # @option options [Boolean] :boolean (false) specifies if this is a boolean parameter # @option options [Symbol] :retrieve the method to call on the provider (or `parent` if `provider` is not set) # to retrieve the current value of this property. # @option options [Symbol, Array<Symbol>] :required_features specifies required provider features by name # @return [Class<inherits Puppet::Property>] the created property # @yield [ ] a required block that is evaluated in the scope of the new property # @api public # @dsl type # def self.newproperty(name, options = {}, &block) name = name.intern # This is here for types that might still have the old method of defining # a parent class. unless options.is_a? Hash raise Puppet::DevError, _("Options must be a hash, not %{type}") % { type: options.inspect } end raise Puppet::DevError, _("Class %{class_name} already has a property named %{property}") % { class_name: self.name, property: name } if @validproperties.include?(name) parent = options[:parent] if parent options.delete(:parent) else parent = Puppet::Property end # We have to create our own, new block here because we want to define # an initial :retrieve method, if told to, and then eval the passed # block if available. prop = genclass(name, :parent => parent, :hash => @validproperties, :attributes => options) do # If they've passed a retrieve method, then override the retrieve # method on the class. if options[:retrieve] define_method(:retrieve) do provider.send(options[:retrieve]) end end class_eval(&block) if block end # If it's the 'ensure' property, always put it first. if name == :ensure @properties.unshift prop else @properties << prop end prop end def self.paramdoc(param) @paramhash[param].doc end # @return [Array<String>] Returns the parameter names def self.parameters return [] unless defined?(@parameters) @parameters.collect(&:name) end # @return [Puppet::Parameter] Returns the parameter class associated with the given parameter name. def self.paramclass(name) @paramhash[name] end # @return [Puppet::Property] Returns the property class ??? associated with the given property name def self.propertybyname(name) @validproperties[name] end # Returns whether or not the given name is the name of a property, parameter or meta-parameter # @return [Boolean] true if the given attribute name is the name of an existing property, parameter or meta-parameter # def self.validattr?(name) name = name.intern return true if name == :name @validattrs ||= {} unless @validattrs.include?(name) @validattrs[name] = !!(validproperty?(name) or validparameter?(name) or metaparam?(name)) end @validattrs[name] end # @return [Boolean] Returns true if the given name is the name of an existing property def self.validproperty?(name) name = name.intern @validproperties.include?(name) && @validproperties[name] end # @return [Array<Symbol>, {}] Returns a list of valid property names, or an empty hash if there are none. # @todo An empty hash is returned if there are no defined parameters (not an empty array). This looks like # a bug. # def self.validproperties return {} unless defined?(@parameters) @validproperties.keys end # @return [Boolean] Returns true if the given name is the name of an existing parameter def self.validparameter?(name) raise Puppet::DevError, _("Class %{class_name} has not defined parameters") % { class_name: self } unless defined?(@parameters) !!(@paramhash.include?(name) or @@metaparamhash.include?(name)) end # (see validattr?) # @note see comment in code - how should this be documented? Are some of the other query methods deprecated? # (or should be). # @comment This is a forward-compatibility method - it's the validity interface we'll use in Puppet::Resource. def self.valid_parameter?(name) validattr?(name) end # @return [Boolean] Returns true if the wanted state of the resource is that it should be absent (i.e. to be deleted). def deleting? obj = @parameters[:ensure] and obj.should == :absent end # Creates a new property value holder for the resource if it is valid and does not already exist # @return [Boolean] true if a new parameter was added, false otherwise def add_property_parameter(prop_name) if self.class.validproperty?(prop_name) && !@parameters[prop_name] newattr(prop_name) return true end false end # @return [Symbol, Boolean] Returns the name of the namevar if there is only one or false otherwise. # @comment This is really convoluted and part of the support for multiple namevars (?). # If there is only one namevar, the produced value is naturally this namevar, but if there are several? # The logic caches the name of the namevar if it is a single name, but otherwise always # calls key_attributes, and then caches the first if there was only one, otherwise it returns # false and caches this (which is then subsequently returned as a cache hit). # def name_var return @name_var_cache unless @name_var_cache.nil? key_attributes = self.class.key_attributes @name_var_cache = (key_attributes.length == 1) && key_attributes.first end # Gets the 'should' (wanted state) value of a parameter or property by name. # To explicitly get the 'is' (current state) value use `o.is(:name)`, and to explicitly get the 'should' value # use `o.should(:name)` # @param name [String] the name of the attribute to obtain the 'should' value for. # @return [Object] 'should'/wanted value of the given attribute def [](name) name = name.intern fail("Invalid parameter #{name}(#{name.inspect})") unless self.class.validattr?(name) if name == :name nv = name_var name = nv if nv end obj = @parameters[name] if obj # Note that if this is a property, then the value is the "should" value, # not the current value. obj.value else nil end end # Sets the 'should' (wanted state) value of a property, or the value of a parameter. # # @raise [Puppet::Error] if the setting of the value fails, or if the given name is nil. # @raise [Puppet::ResourceError] when the parameter validation raises Puppet::Error or # ArgumentError def []=(name, value) name = name.intern fail("no parameter named '#{name}'") unless self.class.validattr?(name) if name == :name nv = name_var name = nv if nv end raise Puppet::Error, "Got nil value for #{name}" if value.nil? property = newattr(name) if property begin # make sure the parameter doesn't have any errors property.value = value rescue Puppet::Error, ArgumentError => detail error = Puppet::ResourceError.new(_("Parameter %{name} failed on %{ref}: %{detail}") % { name: name, ref: ref, detail: detail }) adderrorcontext(error, detail) raise error end end end # Removes an attribute from the object; useful in testing or in cleanup # when an error has been encountered # @todo Don't know what the attr is (name or Property/Parameter?). Guessing it is a String name... # @todo Is it possible to delete a meta-parameter? # @todo What does delete mean? Is it deleted from the type or is its value state 'is'/'should' deleted? # @param attr [String] the attribute to delete from this object. WHAT IS THE TYPE? # @raise [Puppet::DecError] when an attempt is made to delete an attribute that does not exists. # def delete(attr) attr = attr.intern if @parameters.has_key?(attr) @parameters.delete(attr) else raise Puppet::DevError, _("Undefined attribute '%{attribute}' in %{name}") % { attribute: attr, name: self } end end # Iterates over the properties that were set on this resource. # @yieldparam property [Puppet::Property] each property # @return [void] def eachproperty # properties is a private method properties.each { |property| yield property } end # Return the parameters, metaparams, and properties that have a value or were set by a default. Properties are # included since they are a subclass of parameter. # @return [Array<Puppet::Parameter>] Array of parameter objects ( or subclass thereof ) def parameters_with_value self.class.allattrs.filter_map { |attr| parameter(attr) } end # Iterates over all parameters with value currently set. # @yieldparam parameter [Puppet::Parameter] or a subclass thereof # @return [void] def eachparameter parameters_with_value.each { |parameter| yield parameter } end # Creates a transaction event. # Called by Transaction or by a property. # Merges the given options with the options `:resource`, `:file`, `:line`, and `:tags`, initialized from # values in this object. For possible options to pass (if any ????) see {Puppet::Transaction::Event}. # @todo Needs a better explanation "Why should I care who is calling this method?", What do I need to know # about events and how they work? Where can I read about them? # @param options [Hash] options merged with a fixed set of options defined by this method, passed on to {Puppet::Transaction::Event}. # @return [Puppet::Transaction::Event] the created event def event(options = {}) Puppet::Transaction::Event.new(**{ :resource => self, :file => file, :line => line, :tags => tags }.merge(options)) end # @return [Object, nil] Returns the 'should' (wanted state) value for a specified property, or nil if the # given attribute name is not a property (i.e. if it is a parameter, meta-parameter, or does not exist). def should(name) prop = @parameters[name.intern] if prop && prop.is_a?(Puppet::Property) prop.should else nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/network.rb
lib/puppet/network.rb
# frozen_string_literal: true # Just a stub, so we can correctly scope other classes. module Puppet::Network # :nodoc: end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/graph.rb
lib/puppet/graph.rb
# frozen_string_literal: true module Puppet::Graph require_relative 'graph/prioritizer' require_relative 'graph/sequential_prioritizer' require_relative 'graph/simple_graph' require_relative 'graph/rb_tree_map' require_relative 'graph/key' require_relative 'graph/relationship_graph' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/relationship.rb
lib/puppet/relationship.rb
# frozen_string_literal: true # subscriptions are permanent associations determining how different # objects react to an event # This is Puppet's class for modeling edges in its configuration graph. # It used to be a subclass of GRATR::Edge, but that class has weird hash # overrides that dramatically slow down the graphing. class Puppet::Relationship # FormatSupport for serialization methods include Puppet::Network::FormatSupport include Puppet::Util::PsychSupport attr_accessor :source, :target, :callback attr_reader :event def self.from_data_hash(data) source = data['source'] target = data['target'] args = {} args[:event] = :"#{data['event']}" if data["event"] args[:callback] = :"#{data['callback']}" if data["callback"] new(source, target, args) end def event=(event) # TRANSLATORS 'NONE' should not be translated raise ArgumentError, _("You must pass a callback for non-NONE events") if event != :NONE and !callback @event = event end def initialize(source, target, options = {}) @source = source @target = target options = (options || {}).each_with_object({}) { |a, h| h[a[0].to_sym] = a[1]; } [:callback, :event].each do |option| value = options[option] send(option.to_s + "=", value) if value end end # Does the passed event match our event? This is where the meaning # of :NONE comes from. def match?(event) if self.event.nil? or event == :NONE or self.event == :NONE false else self.event == :ALL_EVENTS or event == self.event end end def label result = {} result[:callback] = callback if callback result[:event] = event if event result end def ref "#{source} => #{target}" end def inspect "{ #{source} => #{target} }" end def to_data_hash data = { 'source' => source.to_s, 'target' => target.to_s } data['event'] = event.to_s unless event.nil? data['callback'] = callback.to_s unless callback.nil? data end def to_s ref end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/module_tool.rb
lib/puppet/module_tool.rb
# encoding: UTF-8 # frozen_string_literal: true # Load standard libraries require 'pathname' require 'fileutils' require_relative '../puppet/util/colors' module Puppet module ModuleTool require_relative 'module_tool/tar' extend Puppet::Util::Colors # Directory and names that should not be checksummed. ARTIFACTS = ['pkg', /^\./, /^~/, /^#/, 'coverage', 'checksums.json', 'REVISION'] FULL_MODULE_NAME_PATTERN = %r{\A([^-/|.]+)[-|/](.+)\z} REPOSITORY_URL = Puppet.settings[:module_repository] # Is this a directory that shouldn't be checksummed? # # TODO: Should this be part of Checksums? # TODO: Rename this method to reflect its purpose? # TODO: Shouldn't this be used when building packages too? def self.artifact?(path) case File.basename(path) when *ARTIFACTS true else false end end # Return the +username+ and +modname+ for a given +full_module_name+, or raise an # ArgumentError if the argument isn't parseable. def self.username_and_modname_from(full_module_name) matcher = full_module_name.match(FULL_MODULE_NAME_PATTERN) if matcher matcher.captures else raise ArgumentError, _("Not a valid full name: %{full_module_name}") % { full_module_name: full_module_name } end end # Find the module root when given a path by checking each directory up from # its current location until it finds one that satisfies is_module_root? # # @param path [Pathname, String] path to start from # @return [Pathname, nil] the root path of the module directory or nil if # we cannot find one def self.find_module_root(path) path = Pathname.new(path) if path.instance_of?(String) path.expand_path.ascend do |p| return p if is_module_root?(p) end nil end # Analyse path to see if it is a module root directory by detecting a # file named 'metadata.json' # # @param path [Pathname, String] path to analyse # @return [Boolean] true if the path is a module root, false otherwise def self.is_module_root?(path) path = Pathname.new(path) if path.instance_of?(String) FileTest.file?(path + 'metadata.json') end # Builds a formatted tree from a list of node hashes containing +:text+ # and +:dependencies+ keys. def self.format_tree(nodes, level = 0) str = ''.dup nodes.each_with_index do |node, i| last_node = nodes.length - 1 == i deps = node[:dependencies] || [] str << (indent = " " * level) str << (last_node ? "└" : "├") str << "─" str << (deps.empty? ? "─" : "┬") str << " #{node[:text]}\n" branch = format_tree(deps, level + 1) branch.gsub!(/^#{indent} /, indent + '│') unless last_node str << branch end str end def self.build_tree(mods, dir) mods.each do |mod| version_string = mod[:version].to_s.sub(/^(?!v)/, 'v') if mod[:action] == :upgrade previous_version = mod[:previous_version].to_s.sub(/^(?!v)/, 'v') version_string = "#{previous_version} -> #{version_string}" end mod[:text] = "#{mod[:name]} (#{colorize(:cyan, version_string)})" mod[:text] += " [#{mod[:path]}]" unless mod[:path].to_s == dir.to_s deps = mod[:dependencies] || [] deps.sort_by! { |a| a[:name] } build_tree(deps, dir) end end # @param options [Hash<Symbol,String>] This hash will contain any # command-line arguments that are not Settings, as those will have already # been extracted by the underlying application code. # # @note Unfortunately the whole point of this method is the side effect of # modifying the options parameter. This same hash is referenced both # when_invoked and when_rendering. For this reason, we are not returning # a duplicate. # @todo Validate the above note... # # An :environment_instance and a :target_dir are added/updated in the # options parameter. # # @api private def self.set_option_defaults(options) current_environment = environment_from_options(options) modulepath = [options[:target_dir]] + current_environment.full_modulepath face_environment = current_environment.override_with(:modulepath => modulepath.compact) options[:environment_instance] = face_environment # Note: environment will have expanded the path options[:target_dir] = face_environment.full_modulepath.first end # Given a hash of options, we should discover or create a # {Puppet::Node::Environment} instance that reflects the provided options. # # Generally speaking, the `:modulepath` parameter should supersede all # others, the `:environment` parameter should follow after that, and we # should default to Puppet's current environment. # # @param options [{Symbol => Object}] the options to derive environment from # @return [Puppet::Node::Environment] the environment described by the options def self.environment_from_options(options) if options[:modulepath] path = options[:modulepath].split(File::PATH_SEPARATOR) Puppet::Node::Environment.create(:anonymous, path, '') elsif options[:environment].is_a?(Puppet::Node::Environment) options[:environment] elsif options[:environment] # This use of looking up an environment is correct since it honours # a request to get a particular environment via environment name. Puppet.lookup(:environments).get!(options[:environment]) else Puppet.lookup(:current_environment) end end # Handles parsing of module dependency expressions into proper # {SemanticPuppet::VersionRange}s, including reasonable error handling. # # @param where [String] a description of the thing we're parsing the # dependency expression for # @param dep [Hash] the dependency description to parse # @return [Array(String, SemanticPuppet::VersionRange, String)] a tuple of the # dependent module's name, the version range dependency, and the # unparsed range expression. def self.parse_module_dependency(where, dep) dep_name = dep['name'].tr('/', '-') range = dep['version_requirement'] || '>= 0.0.0' begin parsed_range = Module.parse_range(range) rescue ArgumentError => e Puppet.debug "Error in #{where} parsing dependency #{dep_name} (#{e.message}); using empty range." parsed_range = SemanticPuppet::VersionRange::EMPTY_RANGE end [dep_name, parsed_range, range] end end end # Load remaining libraries require_relative 'module_tool/errors' require_relative 'module_tool/applications' require_relative 'module_tool/checksums' require_relative 'module_tool/contents_description' require_relative 'module_tool/dependency' require_relative 'module_tool/metadata' require_relative '../puppet/forge/cache' require_relative '../puppet/forge'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/interface.rb
lib/puppet/interface.rb
# frozen_string_literal: true require_relative '../puppet' require_relative '../puppet/util/autoload' require 'prettyprint' # @api public class Puppet::Interface require_relative 'interface/documentation' require_relative 'interface/face_collection' require_relative 'interface/action' require_relative 'interface/action_builder' require_relative 'interface/action_manager' require_relative 'interface/option' require_relative 'interface/option_builder' require_relative 'interface/option_manager' include FullDocs include Puppet::Interface::ActionManager extend Puppet::Interface::ActionManager include Puppet::Interface::OptionManager extend Puppet::Interface::OptionManager include Puppet::Util class << self # This is just so we can search for actions. We only use its # list of directories to search. # Lists all loaded faces # @return [Array<Symbol>] The names of the loaded faces def faces Puppet::Interface::FaceCollection.faces end # Register a face # @param instance [Puppet::Interface] The face # @return [void] # @api private def register(instance) Puppet::Interface::FaceCollection.register(instance) end # Defines a new Face. # @todo Talk about using Faces DSL inside the block # # @param name [Symbol] the name of the face # @param version [String] the version of the face (this should # conform to {http://semver.org/ Semantic Versioning}) # @overload define(name, version, { ... }) # @return [Puppet::Interface] The created face # @api public # @dsl Faces def define(name, version, &block) face = Puppet::Interface::FaceCollection[name, version] if face.nil? then face = new(name, version) Puppet::Interface::FaceCollection.register(face) # REVISIT: Shouldn't this be delayed until *after* we evaluate the # current block, not done before? --daniel 2011-04-07 face.load_actions end face.instance_eval(&block) if block_given? face end # Retrieves a face by name and version. Use `:current` for the # version to get the most recent available version. # # @param name [Symbol] the name of the face # @param version [String, :current] the version of the face # # @return [Puppet::Interface] the face # # @api public def face?(name, version) Puppet::Interface::FaceCollection[name, version] end # Retrieves a face by name and version # # @param name [Symbol] the name of the face # @param version [String] the version of the face # # @return [Puppet::Interface] the face # # @api public def [](name, version) face = Puppet::Interface::FaceCollection[name, version] unless face # REVISIT (#18042) no sense in rechecking if version == :current -- josh if Puppet::Interface::FaceCollection[name, :current] raise Puppet::Error, "Could not find version #{version} of #{name}" else raise Puppet::Error, "Could not find Puppet Face #{name}" end end face end # Retrieves an action for a face # @param name [Symbol] The face # @param action [Symbol] The action name # @param version [String, :current] The version of the face # @return [Puppet::Interface::Action] The action def find_action(name, action, version = :current) Puppet::Interface::FaceCollection.get_action_for_face(name, action, version) end end ######################################################################## # Documentation. We currently have to rewrite both getters because we share # the same instance between build-time and the runtime instance. When that # splits out this should merge into a module that both the action and face # include. --daniel 2011-04-17 # Returns the synopsis for the face. This shows basic usage and global # options. # @return [String] usage synopsis # @api private def synopsis build_synopsis name, '<action>' end ######################################################################## # The name of the face # @return [Symbol] # @api private attr_reader :name # The version of the face # @return [SemanticPuppet::Version] attr_reader :version # The autoloader instance for the face # @return [Puppet::Util::Autoload] # @api private attr_reader :loader private :loader # @api private def initialize(name, version, &block) unless SemanticPuppet::Version.valid?(version) raise ArgumentError, _("Cannot create face %{name} with invalid version number '%{version}'!") % { name: name.inspect, version: version } end @name = Puppet::Interface::FaceCollection.underscorize(name) @version = SemanticPuppet::Version.parse(version) # The few bits of documentation we actually demand. The default license # is a favour to our end users; if you happen to get that in a core face # report it as a bug, please. --daniel 2011-04-26 @authors = [] @license = 'All Rights Reserved' @loader = Puppet::Util::Autoload.new(@name, "puppet/face/#{@name}") instance_eval(&block) if block_given? end # Loads all actions defined in other files. # # @return [void] # @api private def load_actions loader.loadall(Puppet.lookup(:current_environment)) end # Returns a string representation with the face's name and version # @return [String] def to_s "Puppet::Face[#{name.inspect}, #{version.inspect}]" end alias_method :inspect, :to_s # @return [void] def deprecate @deprecated = true end # @return [Boolean] def deprecated? @deprecated end ######################################################################## # Action decoration, whee! You are not expected to care about this code, # which exists to support face building and construction. I marked these # private because the implementation is crude and ugly, and I don't yet know # enough to work out how to make it clean. # # Once we have established that these methods will likely change radically, # to be unrecognizable in the final outcome. At which point we will throw # all this away, replace it with something nice, and work out if we should # be making this visible to the outside world... --daniel 2011-04-14 private # @return [void] # @api private def __invoke_decorations(type, action, passed_args = [], passed_options = {}) [:before, :after].member?(type) or fail "unknown decoration type #{type}" # Collect the decoration methods matching our pass. methods = action.options.select do |name| passed_options.has_key? name end.map do |name| action.get_option(name).__decoration_name(type) end methods.reverse! if type == :after # Exceptions here should propagate up; this implements a hook we can use # reasonably for option validation. methods.each do |hook| respond_to? hook and __send__(hook, action, passed_args, passed_options) end end # @return [void] # @api private def __add_method(name, proc) meta_def(name, &proc) method(name).unbind end # @return [void] # @api private def self.__add_method(name, proc) define_method(name, proc) instance_method(name) end private_class_method :__add_method end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parameter.rb
lib/puppet/parameter.rb
# frozen_string_literal: true require_relative '../puppet/util/logging' require_relative '../puppet/util/docs' # The Parameter class is the implementation of a resource's attributes of _parameter_ kind. # The Parameter class is also the base class for {Puppet::Property}, and is used to describe meta-parameters # (parameters that apply to all resource types). # A Parameter (in contrast to a Property) has a single value where a property has both a current and a wanted value. # The Parameter class methods are used to configure and create an instance of Parameter that represents # one particular attribute data type; its valid value(s), and conversion to/from internal form. # # The intention is that a new parameter is created by using the DSL method {Puppet::Type.newparam}, or # {Puppet::Type.newmetaparam} if the parameter should be applicable to all resource types. # # A Parameter that does not specify and valid values (via {newvalues}) accepts any value. # # @see Puppet::Type # @see Puppet::Property # @api public # class Puppet::Parameter include Puppet::Util include Puppet::Util::Errors include Puppet::Util::Logging require_relative 'parameter/value_collection' class << self include Puppet::Util include Puppet::Util::Docs # @return [Symbol] The parameter name as given when it was created. attr_reader :name # @return [Object] The default value of the parameter as determined by the {defaultto} method, or nil if no # default has been set. attr_reader :default # @comment This somewhat odd documentation construct is because the getter and setter are not # orthogonal; the setter uses varargs and this confuses yard. To overcome the problem both the # getter and the setter are documented here. If this issues is fixed, a todo will be displayed # for the setter method, and the setter documentation can be moved there. # Since the attribute is actually RW it should perhaps instead just be implemented as a setter # and a getter method (and no attr_xxx declaration). # # @!attribute [rw] required_features # @return [Array<Symbol>] The names of the _provider features_ required for this parameter to work. # the returned names are always all lower case symbols. # @overload required_features # Returns the required _provider features_ as an array of lower case symbols # @overload required_features=(*args) # @param *args [Symbol] one or more names of required provider features # Sets the required_provider_features_ from one or more values, or array. The given arguments # are flattened, and internalized. # @api public # @dsl type # attr_reader :required_features # @return [Puppet::Parameter::ValueCollection] The set of valid values (or an empty set that accepts any value). # @api private # attr_reader :value_collection # @return [Boolean] Flag indicating whether this parameter is a meta-parameter or not. attr_accessor :metaparam # Defines how the `default` value of a parameter is computed. # The computation of the parameter's default value is defined by providing a value or a block. # A default of `nil` can not be used. # @overload defaultto(value) # Defines the default value with a literal value # @param value [Object] the literal value to use as the default value # @overload defaultto({ ... }) # Defines that the default value is produced by the given block. The given block # should produce the default value. # @raise [Puppet::DevError] if value is nil, and no block is given. # @return [void] # @see Parameter.default # @dsl type # @api public # def defaultto(value = nil, &block) if block define_method(:default, &block) else if value.nil? raise Puppet::DevError, "Either a default value or block must be provided" end define_method(:default) do value end end end # rubocop:disable Naming/PredicateName def sensitive(value = nil, &block) if block define_method(:is_sensitive, &block) else define_method(:is_sensitive) do value end end end # rubocop:enable Naming/PredicateName # Produces a documentation string. # If an enumeration of _valid values_ has been defined, it is appended to the documentation # for this parameter specified with the {desc} method. # @return [String] Returns a documentation string. # @api public # def doc @doc ||= "" unless defined?(@addeddocvals) @doc = Puppet::Util::Docs.scrub(@doc) vals = value_collection.doc if vals @doc << "\n\n#{vals}" end features = required_features if features @doc << "\n\nRequires features #{features.flatten.collect(&:to_s).join(' ')}." end @addeddocvals = true end @doc end # Removes the `default` method if defined. # Has no effect if the default method is not defined. # This method is intended to be used in a DSL scenario where a parameter inherits from a parameter # with a default value that is not wanted in the derived parameter (otherwise, simply do not define # a default value method). # # @return [void] # @see desc # @api public # @dsl type # def nodefault undef_method :default if public_method_defined? :default end # Sets the documentation for this parameter. # @param str [String] The documentation string to set # @return [String] the given `str` parameter # @see doc # @dsl type # @api public # def desc(str) @doc = str end # Initializes the instance variables. # Clears the internal value collection (set of allowed values). # @return [void] # @api private # def initvars @value_collection = ValueCollection.new end # @overload munge { ... } # Defines an optional method used to convert the parameter value from DSL/string form to an internal form. # If a munge method is not defined, the DSL/string value is used as is. # @note This adds a method with the name `unsafe_munge` in the created parameter class. Later this method is # called in a context where exceptions will be rescued and handled. # @dsl type # @api public # def munge(&block) # I need to wrap the unsafe version in begin/rescue parameterments, # but if I directly call the block then it gets bound to the # class's context, not the instance's, thus the two methods, # instead of just one. define_method(:unsafe_munge, &block) end # @overload unmunge { ... } # Defines an optional method used to convert the parameter value from internal form to DSL/string form. # If an `unmunge` method is not defined, the internal form is used. # @see munge # @note This adds a method with the name `unsafe_unmunge` in the created parameter class. # @dsl type # @api public # def unmunge(&block) define_method(:unsafe_unmunge, &block) end # Sets a marker indicating that this parameter is the _namevar_ (unique identifier) of the type # where the parameter is contained. # This also makes the parameter a required value. The marker can not be unset once it has been set. # @return [void] # @dsl type # @api public # def isnamevar @isnamevar = true @required = true end # @return [Boolean] Returns whether this parameter is the _namevar_ or not. # @api public # def isnamevar? @isnamevar end # Sets a marker indicating that this parameter is required. # Once set, it is not possible to make a parameter optional. # @return [void] # @dsl type # @api public # def isrequired @required = true end # @comment This method is not picked up by yard as it has a different signature than # expected for an attribute (varargs). Instead, this method is documented as an overload # of the attribute required_features. (Not ideal, but better than nothing). # @todo If this text appears in documentation - see comment in source and makes corrections - it means # that an issue in yardoc has been fixed. # def required_features=(*args) @required_features = args.flatten.collect { |a| a.to_s.downcase.intern } end # Returns whether this parameter is required or not. # A parameter is required if a call has been made to the DSL method {isrequired}. # @return [Boolean] Returns whether this parameter is required or not. # @api public # def required? @required end # @overload validate { ... } # Defines an optional method that is used to validate the parameter's DSL/string value. # Validation should raise appropriate exceptions, the return value of the given block is ignored. # The easiest way to raise an appropriate exception is to call the method {Puppet::Util::Errors.fail} with # the message as an argument. # To validate the munged value instead, just munge the value (`munge(value)`). # # @return [void] # @dsl type # @api public # def validate(&block) define_method(:unsafe_validate, &block) end # Defines valid values for the parameter (enumeration or regular expressions). # The set of valid values for the parameter can be limited to a (mix of) literal values and # regular expression patterns. # @note Each call to this method adds to the set of valid values # @param names [Symbol, Regexp] The set of valid literal values and/or patterns for the parameter. # @return [void] # @dsl type # @api public # def newvalues(*names) @value_collection.newvalues(*names) end # Makes the given `name` an alias for the given `other` name. # Or said differently, the valid value `other` can now also be referred to via the given `name`. # Aliasing may affect how the parameter's value is serialized/stored (it may store the `other` value # instead of the alias). # @api public # @dsl type # def aliasvalue(name, other) @value_collection.aliasvalue(name, other) end end # Creates instance (proxy) methods that delegates to a class method with the same name. # @api private # def self.proxymethods(*values) values.each { |val| define_method(val) do self.class.send(val) end } end # @!method required? # (see required?) # @!method isnamevar? # (see isnamevar?) # proxymethods("required?", "isnamevar?") # @return [Puppet::Resource] A reference to the resource this parameter is an attribute of (the _associated resource_). attr_accessor :resource # @comment LAK 2007-05-09: Keep the @parent around for backward compatibility. # @return [Puppet::Parameter] A reference to the parameter's parent kept for backwards compatibility. # @api private # attr_accessor :parent # @!attribute [rw] sensitive # @return [true, false] If this parameter has been tagged as sensitive. attr_accessor :sensitive # Returns a string representation of the resource's containment path in # the catalog. # @return [String] def path @path ||= '/' + pathbuilder.join('/') end # @return [Integer] Returns the result of calling the same method on the associated resource. def line resource.line end # @return [Integer] Returns the result of calling the same method on the associated resource. def file resource.file end # @return [Integer] Returns the result of calling the same method on the associated resource. def version resource.version end # Initializes the parameter with a required resource reference and optional attribute settings. # The option `:resource` must be specified or an exception is raised. Any additional options passed # are used to initialize the attributes of this parameter by treating each key in the `options` hash as # the name of the attribute to set, and the value as the value to set. # @param options [Hash{Symbol => Object]] Options, where `resource` is required # @option options [Puppet::Resource] :resource The resource this parameter holds a value for. Required. # @raise [Puppet::DevError] If resource is not specified in the options hash. # @api public # @note A parameter should be created via the DSL method {Puppet::Type::newparam} # def initialize(resource: nil, value: nil, should: nil) if resource self.resource = resource else raise Puppet::DevError, _("No resource set for %{name}") % { name: self.class.name } end self.value = value if value self.should = should if should end # Writes the given `msg` to the log with the loglevel indicated by the associated resource's # `loglevel` parameter. # @todo is loglevel a metaparameter? it is looked up with `resource[:loglevel]` # @return [void] # @api public def log(msg) send_log(resource[:loglevel], msg) end # @return [Boolean] Returns whether this parameter is a meta-parameter or not. def metaparam? self.class.metaparam end # @!attribute [r] name # @return [Symbol] The parameter's name as given when it was created. # @note Since a Parameter defines the name at the class level, each Parameter class must be # unique within a type's inheritance chain. # @comment each parameter class must define the name method, and parameter # instances do not change that name this implicitly means that a given # object can only have one parameter instance of a given parameter # class def name self.class.name end # @return [Boolean] Returns true if this parameter, the associated resource, or overall puppet mode is `noop`. # @todo How is noop mode set for a parameter? Is this of value in DSL to inhibit a parameter? # def noop @noop ||= false @noop || resource.noop || Puppet[:noop] || false end # Returns an array of strings representing the containment hierarchy # (types/classes) that make up the path to the resource from the root # of the catalog. This is mostly used for logging purposes. # # @api private def pathbuilder if @resource [@resource.pathbuilder, name] else [name] end end # This is the default implementation of `munge` that simply produces the value (if it is valid). # The DSL method {munge} should be used to define an overriding method if munging is required. # # @api private # def unsafe_munge(value) self.class.value_collection.munge(value) end # Unmunges the value by transforming it from internal form to DSL form. # This is the default implementation of `unmunge` that simply returns the value without processing. # The DSL method {unmunge} should be used to define an overriding method if required. # @return [Object] the unmunged value # def unmunge(value) return value if value.is_a?(Puppet::Pops::Evaluator::DeferredValue) unsafe_unmunge(value) end # This is the default implementation of `unmunge` that simply produces the value (if it is valid). # The DSL method {unmunge} should be used to define an overriding method if unmunging is required. # # @api private # def unsafe_unmunge(value) value end # Munges the value from DSL form to internal form. # This implementation of `munge` provides exception handling around the specified munging of this parameter. # @note This method should not be overridden. Use the DSL method {munge} to define a munging method # if required. # @param value [Object] the DSL value to munge # @return [Object] the munged (internal) value # def munge(value) return value if value.is_a?(Puppet::Pops::Evaluator::DeferredValue) begin ret = unsafe_munge(value) rescue Puppet::Error => detail Puppet.debug { "Reraising #{detail}" } raise rescue => detail raise Puppet::DevError, _("Munging failed for value %{value} in class %{class_name}: %{detail}") % { value: value.inspect, class_name: name, detail: detail }, detail.backtrace end ret end # This is the default implementation of `validate` that may be overridden by the DSL method {validate}. # If no valid values have been defined, the given value is accepted, else it is validated against # the literal values (enumerator) and/or patterns defined by calling {newvalues}. # # @param value [Object] the value to check for validity # @raise [ArgumentError] if the value is not valid # @return [void] # @api private # def unsafe_validate(value) self.class.value_collection.validate(value) end # Performs validation of the given value against the rules defined by this parameter. # @return [void] # @todo Better description of when the various exceptions are raised.ArgumentError is rescued and # changed into Puppet::Error. # @raise [ArgumentError, TypeError, Puppet::DevError, Puppet::Error] under various conditions # A protected validation method that only ever raises useful exceptions. # @api public # def validate(value) return if value.is_a?(Puppet::Pops::Evaluator::DeferredValue) begin unsafe_validate(value) rescue ArgumentError => detail self.fail Puppet::Error, detail.to_s, detail rescue Puppet::Error, TypeError raise rescue => detail raise Puppet::DevError, _("Validate method failed for class %{class_name}: %{detail}") % { class_name: name, detail: detail }, detail.backtrace end end # Sets the associated resource to nil. # @todo Why - what is the intent/purpose of this? # @return [nil] # def remove @resource = nil end # @return [Object] Gets the value of this parameter after performing any specified unmunging. def value unmunge(@value) unless @value.nil? end # Sets the given value as the value of this parameter. # @todo This original comment _"All of the checking should possibly be # late-binding (e.g., users might not exist when the value is assigned # but might when it is asked for)."_ does not seem to be correct, the implementation # calls both validate and munge on the given value, so no late binding. # # The given value is validated and then munged (if munging has been specified). The result is store # as the value of this parameter. # @return [Object] The given `value` after munging. # @raise (see #validate) # def value=(value) validate(value) @value = munge(value) end # @return [Puppet::Provider] Returns the provider of the associated resource. # @todo The original comment says = _"Retrieve the resource's provider. # Some types don't have providers, in which case we return the resource object itself."_ # This does not seem to be true, the default implementation that sets this value may be # {Puppet::Type.provider=} which always gets either the name of a provider or an instance of one. # def provider @resource.provider end # @return [Array<Symbol>] Returns an array of the associated resource's symbolic tags (including the parameter itself). # Returns an array of the associated resource's symbolic tags (including the parameter itself). # At a minimum, the array contains the name of the parameter. If the associated resource # has tags, these tags are also included in the array. # @todo The original comment says = _"The properties need to return tags so that logs correctly # collect them."_ what if anything of that is of interest to document. Should tags and their relationship # to logs be described. This is a more general concept. # def tags unless defined?(@tags) @tags = [] # This might not be true in testing @tags = @resource.tags if @resource.respond_to? :tags @tags << name.to_s end @tags end # @return [String] The name of the parameter in string form. def to_s name.to_s end # Formats the given string and conditionally redacts the provided interpolation variables, depending on if # this property is sensitive. # # @note Because the default implementation of Puppet::Property#is_to_s returns the current value as-is, it # doesn't necessarily return a string. For the sake of sanity we just cast everything to a string for # interpolation so we don't introduce issues with unexpected property values. # # @see String#format # @param fmt [String] The format string to interpolate. # @param args [Array<String>] One or more strings to conditionally redact and interpolate into the format string. # # @return [String] def format(fmt, *args) fmt % args.map { |arg| @sensitive ? "[redacted]" : arg.to_s } end # Produces a String with the value formatted for display to a human. # # The output is created using the StringConverter with format '%#p' to produce # human readable code that is understood by puppet. # # @return [String] The formatted value in string form. # def self.format_value_for_display(value) Puppet::Pops::Types::StringConverter.convert(value, Puppet::Pops::Types::StringConverter::DEFAULT_PARAMETER_FORMAT) end # @comment Document post_compile_hook here as it does not exist anywhere (called from type if implemented) # @!method post_compile() # @since 3.4.0 # @api public # @abstract A subclass may implement this - it is not implemented in the Parameter class # This method may be implemented by a parameter in order to perform actions during compilation # after all resources have been added to the catalog. # @see Puppet::Type#finish # @see Puppet::Parser::Compiler#finish end require_relative 'parameter/path'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/node.rb
lib/puppet/node.rb
# frozen_string_literal: true require_relative '../puppet/indirector' # A class for managing nodes, including their facts and environment. class Puppet::Node require_relative 'node/facts' require_relative 'node/environment' # Set up indirection, so that nodes can be looked for in # the node sources. extend Puppet::Indirector # Asymmetric serialization/deserialization required in this class via to/from datahash include Puppet::Util::PsychSupport # Use the node source as the indirection terminus. indirects :node, :terminus_setting => :node_terminus, :doc => "Where to find node information. A node is composed of its name, its facts, and its environment." attr_accessor :name, :classes, :source, :ipaddress, :parameters, :environment_name attr_reader :time, :facts, :trusted_data attr_reader :server_facts ENVIRONMENT = 'environment' def initialize_from_hash(data) @name = data['name'] || (raise ArgumentError, _("No name provided in serialized data")) @classes = data['classes'] || [] @parameters = data['parameters'] || {} env_name = data['environment'] || @parameters[ENVIRONMENT] unless env_name.nil? @parameters[ENVIRONMENT] = env_name @environment_name = env_name.intern end end def self.from_data_hash(data) node = new(name) node.initialize_from_hash(data) node end def to_data_hash result = { 'name' => name, 'environment' => environment.name.to_s, } result['classes'] = classes unless classes.empty? serialized_params = serializable_parameters result['parameters'] = serialized_params unless serialized_params.empty? result end def serializable_parameters new_params = parameters.dup new_params.delete(ENVIRONMENT) new_params end def environment unless @environment env = parameters[ENVIRONMENT] if env self.environment = env elsif environment_name self.environment = environment_name else # This should not be :current_environment, this is the default # for a node when it has not specified its environment # it will be used to establish what the current environment is. # self.environment = Puppet.lookup(:environments).get!(Puppet[:environment]) end end @environment end def environment=(env) if env.is_a?(String) or env.is_a?(Symbol) @environment = Puppet.lookup(:environments).get!(env) else @environment = env end # Keep environment_name attribute and parameter in sync if they have been set unless @environment.nil? # always set the environment parameter. It becomes top scope $environment for a manifest during catalog compilation. @parameters[ENVIRONMENT] = @environment.name.to_s self.environment_name = @environment.name end end def has_environment_instance? !@environment.nil? end def initialize(name, options = {}) raise ArgumentError, _("Node names cannot be nil") unless name @name = name classes = options[:classes] if classes if classes.is_a?(String) @classes = [classes] else @classes = classes end else @classes = [] end @parameters = options[:parameters] || {} @facts = options[:facts] @server_facts = {} env = options[:environment] if env self.environment = env end @time = Time.now end # Merge the node facts with parameters from the node source. # @api public # @param facts [optional, Puppet::Node::Facts] facts to merge into node parameters. # Will query Facts indirection if not supplied. # @raise [Puppet::Error] Raise on failure to retrieve facts if not supplied # @return [nil] def fact_merge(facts = nil) begin @facts = facts.nil? ? Puppet::Node::Facts.indirection.find(name, :environment => environment) : facts rescue => detail error = Puppet::Error.new(_("Could not retrieve facts for %{name}: %{detail}") % { name: name, detail: detail }, detail) error.set_backtrace(detail.backtrace) raise error end unless @facts.nil? @facts.sanitize # facts should never modify the environment parameter orig_param_env = @parameters[ENVIRONMENT] merge(@facts.values) @parameters[ENVIRONMENT] = orig_param_env end end # Merge any random parameters into our parameter list. def merge(params) params.each do |name, value| if @parameters.include?(name) Puppet::Util::Warnings.warnonce(_("The node parameter '%{param_name}' for node '%{node_name}' was already set to '%{value}'. It could not be set to '%{desired_value}'") % { param_name: name, node_name: @name, value: @parameters[name], desired_value: value }) else @parameters[name] = value end end end # Add extra facts, such as facts given to lookup on the command line The # extra facts will override existing ones. # @param extra_facts [Hash{String=>Object}] the facts to tadd # @api private def add_extra_facts(extra_facts) @facts.add_extra_values(extra_facts) @parameters.merge!(extra_facts) nil end def add_server_facts(facts) # Append the current environment to the list of server facts @server_facts = facts.merge({ "environment" => environment.name.to_s }) # Merge the server facts into the parameters for the node merge(facts) end # Calculate the list of names we might use for looking # up our node. This is only used for AST nodes. def names @names ||= [name] end def split_name(name) list = name.split(".") tmp = [] list.each_with_index do |_short, i| tmp << list[0..i].join(".") end tmp.reverse end # Ensures the data is frozen # def trusted_data=(data) Puppet.warning(_("Trusted node data modified for node %{name}") % { name: name }) unless @trusted_data.nil? @trusted_data = data.freeze end # Resurrects and sanitizes trusted information in the node by modifying it and setting # the trusted_data in the node from parameters. # This modifies the node # def sanitize # Resurrect "trusted information" that comes from node/fact terminus. # The current way this is done in puppet db (currently the only one) # is to store the node parameter 'trusted' as a hash of the trusted information. # # Thus here there are two main cases: # 1. This terminus was used in a real agent call (only meaningful if someone curls the request as it would # fail since the result is a hash of two catalogs). # 2 It is a command line call with a given node that use a terminus that: # 2.1 does not include a 'trusted' fact - use local from node trusted information # 2.2 has a 'trusted' fact - this in turn could be # 2.2.1 puppet db having stored trusted node data as a fact (not a great design) # 2.2.2 some other terminus having stored a fact called "trusted" (most likely that would have failed earlier, but could # be spoofed). # # For the reasons above, the resurrection of trusted node data with authenticated => true is only performed # if user is running as root, else it is resurrected as unauthenticated. # trusted_param = @parameters['trusted'] if trusted_param # Blows up if it is a parameter as it will be set as $trusted by the compiler as if it was a variable @parameters.delete('trusted') unless trusted_param.is_a?(Hash) && %w[authenticated certname extensions].all? { |key| trusted_param.has_key?(key) } # trusted is some kind of garbage, do not resurrect trusted_param = nil end else # trusted may be Boolean false if set as a fact by someone trusted_param = nil end # The options for node.trusted_data in priority order are: # 1) node came with trusted_data so use that # 2) else if there is :trusted_information in the puppet context # 3) else if the node provided a 'trusted' parameter (parsed out above) # 4) last, fallback to local node trusted information # # Note that trusted_data should be a hash, but (2) and (4) are not # hashes, so we to_h at the end unless trusted_data trusted = Puppet.lookup(:trusted_information) do trusted_param || Puppet::Context::TrustedInformation.local(self) end self.trusted_data = trusted.to_h end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/syntax_checkers.rb
lib/puppet/syntax_checkers.rb
# frozen_string_literal: true # A name space for syntax checkers provided by Puppet. module Puppet::SyntaxCheckers end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/transaction.rb
lib/puppet/transaction.rb
# frozen_string_literal: true require_relative '../puppet' require_relative '../puppet/util/tagging' require_relative '../puppet/util/skip_tags' require_relative '../puppet/application' require 'digest/sha1' require 'set' # the class that actually walks our resource/property tree, collects the changes, # and performs them # # @api private class Puppet::Transaction require_relative 'transaction/additional_resource_generator' require_relative 'transaction/event' require_relative 'transaction/event_manager' require_relative 'transaction/resource_harness' require_relative '../puppet/resource/status' require_relative 'transaction/persistence' attr_accessor :catalog, :ignoreschedules, :for_network_device # The report, once generated. attr_reader :report # Routes and stores any events and subscriptions. attr_reader :event_manager # Handles most of the actual interacting with resources attr_reader :resource_harness attr_reader :prefetched_providers, :prefetch_failed_providers # @!attribute [r] persistence # @return [Puppet::Transaction::Persistence] persistence object for cross # transaction storage. attr_reader :persistence include Puppet::Util include Puppet::Util::Tagging def initialize(catalog, report, prioritizer) @catalog = catalog @persistence = Puppet::Transaction::Persistence.new @report = report || Puppet::Transaction::Report.new(catalog.version, catalog.environment) @prioritizer = prioritizer @report.add_times(:config_retrieval, @catalog.retrieval_duration || 0) @event_manager = Puppet::Transaction::EventManager.new(self) @resource_harness = Puppet::Transaction::ResourceHarness.new(self) @prefetched_providers = Hash.new { |h, k| h[k] = {} } @prefetch_failed_providers = Hash.new { |h, k| h[k] = {} } # With merge_dependency_warnings, notify and warn about class dependency failures ... just once per class. TJK 2019-09-09 @merge_dependency_warnings = Puppet[:merge_dependency_warnings] @failed_dependencies_already_notified = Set.new() @failed_class_dependencies_already_notified = Set.new() @failed_class_dependencies_already_warned = Set.new() end # Invoke the pre_run_check hook in every resource in the catalog. # This should (only) be called by Transaction#evaluate before applying # the catalog. # # @see Puppet::Transaction#evaluate # @see Puppet::Type#pre_run_check # @raise [Puppet::Error] If any pre-run checks failed. # @return [void] def perform_pre_run_checks prerun_errors = {} @catalog.vertices.each do |res| res.pre_run_check rescue Puppet::Error => detail prerun_errors[res] = detail end unless prerun_errors.empty? prerun_errors.each do |res, detail| res.log_exception(detail) end raise Puppet::Error, _("Some pre-run checks failed") end end # This method does all the actual work of running a transaction. It # collects all of the changes, executes them, and responds to any # necessary events. def evaluate(&block) block ||= method(:eval_resource) generator = AdditionalResourceGenerator.new(@catalog, nil, @prioritizer) @catalog.vertices.each { |resource| generator.generate_additional_resources(resource) } perform_pre_run_checks persistence.load if persistence.enabled?(catalog) Puppet.info _("Applying configuration version '%{version}'") % { version: catalog.version } if catalog.version continue_while = -> { !stop_processing? } post_evalable_providers = Set.new pre_process = lambda do |resource| prov_class = resource.provider.class post_evalable_providers << prov_class if prov_class.respond_to?(:post_resource_eval) prefetch_if_necessary(resource) # If we generated resources, we don't know what they are now # blocking, so we opt to recompute it, rather than try to track every # change that would affect the number. relationship_graph.clear_blockers if generator.eval_generate(resource) end providerless_types = [] overly_deferred_resource_handler = lambda do |resource| # We don't automatically assign unsuitable providers, so if there # is one, it must have been selected by the user. return if missing_tags?(resource) if resource.provider resource.err _("Provider %{name} is not functional on this host") % { name: resource.provider.class.name } else providerless_types << resource.type end resource_status(resource).failed = true end canceled_resource_handler = lambda do |resource| resource_status(resource).skipped = true resource.debug "Transaction canceled, skipping" end teardown = lambda do # Just once per type. No need to punish the user. providerless_types.uniq.each do |type| Puppet.err _("Could not find a suitable provider for %{type}") % { type: type } end post_evalable_providers.each do |provider| provider.post_resource_eval rescue => detail Puppet.log_exception(detail, _("post_resource_eval failed for provider %{provider}") % { provider: provider }) end persistence.save if persistence.enabled?(catalog) end # Graph cycles are returned as an array of arrays # - outer array is an array of cycles # - each inner array is an array of resources involved in a cycle # Short circuit resource evaluation if we detect cycle(s) in the graph. Mark # each corresponding resource as failed in the report before we fail to # ensure accurate reporting. graph_cycle_handler = lambda do |cycles| cycles.flatten.uniq.each do |resource| # We add a failed resource event to the status to ensure accurate # reporting through the event manager. resource_status(resource).fail_with_event(_('resource is part of a dependency cycle')) end raise Puppet::Error, _('One or more resource dependency cycles detected in graph') end # Generate the relationship graph, set up our generator to use it # for eval_generate, then kick off our traversal. generator.relationship_graph = relationship_graph progress = 0 relationship_graph.traverse(:while => continue_while, :pre_process => pre_process, :overly_deferred_resource_handler => overly_deferred_resource_handler, :canceled_resource_handler => canceled_resource_handler, :graph_cycle_handler => graph_cycle_handler, :teardown => teardown) do |resource| progress += 1 if resource.is_a?(Puppet::Type::Component) Puppet.warning _("Somehow left a component in the relationship graph") else if Puppet[:evaltrace] && @catalog.host_config? resource.info _("Starting to evaluate the resource (%{progress} of %{total})") % { progress: progress, total: relationship_graph.size } end seconds = thinmark { block.call(resource) } resource.info _("Evaluated in %{seconds} seconds") % { seconds: "%0.2f" % seconds } if Puppet[:evaltrace] && @catalog.host_config? end end # if one or more resources has attempted and failed to generate resources, # report it if generator.resources_failed_to_generate report.resources_failed_to_generate = true end # mark the end of transaction evaluate. report.transaction_completed = true Puppet.debug { "Finishing transaction #{object_id}" } end # Wraps application run state check to flag need to interrupt processing def stop_processing? Puppet::Application.stop_requested? && catalog.host_config? end # Are there any failed resources in this transaction? def any_failed? report.resource_statuses.values.detect { |status| status.failed? || status.failed_to_restart? } end # Find all of the changed resources. def changed? report.resource_statuses.values.find_all(&:changed).collect { |status| catalog.resource(status.resource) } end def relationship_graph catalog.relationship_graph(@prioritizer) end def resource_status(resource) report.resource_statuses[resource.to_s] || add_resource_status(Puppet::Resource::Status.new(resource)) end # The tags we should be checking. def tags self.tags = Puppet[:tags] unless defined?(@tags) super end def skip_tags @skip_tags ||= Puppet::Util::SkipTags.new(Puppet[:skip_tags]).tags end def prefetch_if_necessary(resource) provider_class = resource.provider.class if !provider_class.respond_to?(:prefetch) or prefetched_providers[resource.type][provider_class.name] or prefetch_failed_providers[resource.type][provider_class.name] return end resources = resources_by_provider(resource.type, provider_class.name) if provider_class == resource.class.defaultprovider providerless_resources = resources_by_provider(resource.type, nil) providerless_resources.values.each { |res| res.provider = provider_class.name } resources.merge! providerless_resources end prefetch(provider_class, resources) end private # Apply all changes for a resource def apply(resource, ancestor = nil) status = resource_harness.evaluate(resource) add_resource_status(status) ancestor ||= resource unless status.failed? || status.failed_to_restart? event_manager.queue_events(ancestor, status.events) end rescue => detail resource.err _("Could not evaluate: %{detail}") % { detail: detail } end # Evaluate a single resource. def eval_resource(resource, ancestor = nil) resolve_resource(resource) propagate_failure(resource) if skip?(resource) resource_status(resource).skipped = true resource.debug("Resource is being skipped, unscheduling all events") event_manager.dequeue_all_events_for_resource(resource) persistence.copy_skipped(resource.ref) else resource_status(resource).scheduled = true apply(resource, ancestor) event_manager.process_events(resource) end end # Does this resource have any failed dependencies? def failed_dependencies?(resource) # When we introduced the :whit into the graph, to reduce the combinatorial # explosion of edges, we also ended up reporting failures for containers # like class and stage. This is undesirable; while just skipping the # output isn't perfect, it is RC-safe. --daniel 2011-06-07 is_puppet_class = resource.instance_of?(Puppet::Type.type(:whit)) # With merge_dependency_warnings, notify about class dependency failures ... just once per class. TJK 2019-09-09 s = resource_status(resource) if s && s.dependency_failed? if @merge_dependency_warnings && is_puppet_class # Notes: Puppet::Resource::Status.failed_dependencies() is an Array of # Puppet::Resource(s) and Puppet::Resource.ref() calls # Puppet::Resource.to_s() which is: "#{type}[#{title}]" and # Puppet::Resource.resource_status(resource) calls # Puppet::Resource.to_s() class_dependencies_to_be_notified = (s.failed_dependencies.map(&:ref) - @failed_class_dependencies_already_notified.to_a) class_dependencies_to_be_notified.each do |dep_ref| resource.notice _("Class dependency %{dep} has failures: %{status}") % { dep: dep_ref, status: resource_status(dep_ref).failed } end @failed_class_dependencies_already_notified.merge(class_dependencies_to_be_notified) else unless @merge_dependency_warnings || is_puppet_class s.failed_dependencies.find_all { |d| !@failed_dependencies_already_notified.include?(d.ref) }.each do |dep| resource.notice _("Dependency %{dep} has failures: %{status}") % { dep: dep, status: resource_status(dep).failed } @failed_dependencies_already_notified.add(dep.ref) end end end end s && s.dependency_failed? end # We need to know if a resource has any failed dependencies before # we try to process it. We keep track of this by keeping a list on # each resource of the failed dependencies, and incrementally # computing it as the union of the failed dependencies of each # first-order dependency. We have to do this as-we-go instead of # up-front at failure time because the graph may be mutated as we # walk it. def propagate_failure(resource) provider_class = resource.provider.class s = resource_status(resource) if prefetch_failed_providers[resource.type][provider_class.name] && !s.nil? message = _("Prefetch failed for %{type_name} provider '%{name}'") % { type_name: resource.type, name: provider_class.name } s.fail_with_event(message) end failed = Set.new relationship_graph.direct_dependencies_of(resource).each do |dep| s = resource_status(dep) next if s.nil? failed.merge(s.failed_dependencies) if s.dependency_failed? failed.add(dep) if s.failed? || s.failed_to_restart? end resource_status(resource).failed_dependencies = failed.to_a end # Should we ignore tags? def ignore_tags? !@catalog.host_config? end def resources_by_provider(type_name, provider_name) unless @resources_by_provider @resources_by_provider = Hash.new { |h, k| h[k] = Hash.new { |h1, k1| h1[k1] = {} } } @catalog.vertices.each do |resource| if resource.class.attrclass(:provider) prov = resource.provider && resource.provider.class.name @resources_by_provider[resource.type][prov][resource.name] = resource end end end @resources_by_provider[type_name][provider_name] || {} end # Prefetch any providers that support it, yo. We don't support prefetching # types, just providers. def prefetch(provider_class, resources) type_name = provider_class.resource_type.name return if @prefetched_providers[type_name][provider_class.name] || @prefetch_failed_providers[type_name][provider_class.name] Puppet.debug { "Prefetching #{provider_class.name} resources for #{type_name}" } begin provider_class.prefetch(resources) rescue LoadError, StandardError => detail # TRANSLATORS `prefetch` is a function name and should not be translated message = _("Could not prefetch %{type_name} provider '%{name}': %{detail}") % { type_name: type_name, name: provider_class.name, detail: detail } Puppet.log_exception(detail, message) @prefetch_failed_providers[type_name][provider_class.name] = true end @prefetched_providers[type_name][provider_class.name] = true end def add_resource_status(status) report.add_resource_status(status) end # Is the resource currently scheduled? def scheduled?(resource) ignoreschedules || resource_harness.scheduled?(resource) end # Should this resource be skipped? def skip?(resource) if skip_tags?(resource) resource.debug "Skipping with skip tags #{skip_tags.join(', ')}" elsif missing_tags?(resource) resource.debug "Not tagged with #{tags.join(', ')}" elsif !scheduled?(resource) resource.debug "Not scheduled" elsif failed_dependencies?(resource) # When we introduced the :whit into the graph, to reduce the combinatorial # explosion of edges, we also ended up reporting failures for containers # like class and stage. This is undesirable; while just skipping the # output isn't perfect, it is RC-safe. --daniel 2011-06-07 # With merge_dependency_warnings, warn about class dependency failures ... just once per class. TJK 2019-09-09 unless resource.instance_of?(Puppet::Type.type(:whit)) if @merge_dependency_warnings && resource.parent && failed_dependencies?(resource.parent) ps = resource_status(resource.parent) ps.failed_dependencies.find_all { |d| !@failed_class_dependencies_already_warned.include?(d.ref) }.each do |dep| resource.parent.warning _("Skipping resources in class because of failed class dependencies") @failed_class_dependencies_already_warned.add(dep.ref) end else resource.warning _("Skipping because of failed dependencies") end end elsif resource_status(resource).failed? && @prefetch_failed_providers[resource.type][resource.provider.class.name] # Do not try to evaluate a resource with a known failed provider resource.warning _("Skipping because provider prefetch failed") elsif resource.virtual? resource.debug "Skipping because virtual" elsif !host_and_device_resource?(resource) && resource.appliable_to_host? && for_network_device resource.debug "Skipping host resources because running on a device" elsif !host_and_device_resource?(resource) && resource.appliable_to_device? && !for_network_device resource.debug "Skipping device resources because running on a posix host" else return false end true end def host_and_device_resource?(resource) resource.appliable_to_host? && resource.appliable_to_device? end # Is this resource tagged appropriately? def missing_tags?(resource) return false if ignore_tags? return false if tags.empty? !resource.tagged?(*tags) end def skip_tags?(resource) return false if ignore_tags? return false if skip_tags.empty? resource.tagged?(*skip_tags) end def split_qualified_tags? false end # These two methods are only made public to enable the existing spec tests to run # under rspec 3 (apparently rspec 2 didn't enforce access controls?). Please do not # treat these as part of a public API. # Possible future improvement: rewrite to not require access to private methods. public :skip? public :missing_tags? def resolve_resource(resource) return unless catalog.host_config? deferred_validate = false resource.eachparameter do |param| if param.value.instance_of?(Puppet::Pops::Evaluator::DeferredValue) # Puppet::Parameter#value= triggers validation and munging. Puppet::Property#value= # overrides the method, but also triggers validation and munging, since we're # setting the desired/should value. resolved = param.value.resolve # resource.notice("Resolved deferred value to #{resolved}") param.value = resolved deferred_validate = true end end if deferred_validate resource.validate_resource end end end require_relative 'transaction/report'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/scheduler.rb
lib/puppet/scheduler.rb
# frozen_string_literal: true module Puppet::Scheduler require_relative 'scheduler/job' require_relative 'scheduler/splay_job' require_relative 'scheduler/scheduler' require_relative 'scheduler/timer' module_function def create_job(interval, splay = false, splay_limit = 0, &block) if splay Puppet::Scheduler::SplayJob.new(interval, splay_limit, &block) else Puppet::Scheduler::Job.new(interval, &block) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl.rb
lib/puppet/ssl.rb
# frozen_string_literal: true # Just to make the constants work out. require_relative '../puppet' require_relative 'ssl/openssl_loader' # Responsible for bootstrapping an agent's certificate and private key, generating # SSLContexts for use in making HTTPS connections, and handling CSR attributes and # certificate extensions. # # @see Puppet::SSL::SSLProvider # @api private module Puppet::SSL CA_NAME = "ca" require_relative 'ssl/oids' require_relative 'ssl/error' require_relative 'ssl/ssl_context' require_relative 'ssl/verifier' require_relative 'ssl/ssl_provider' require_relative 'ssl/state_machine' require_relative 'ssl/certificate' require_relative 'ssl/certificate_request' require_relative 'ssl/certificate_request_attributes' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parser.rb
lib/puppet/parser.rb
# frozen_string_literal: true # is only needed to create the name space module Puppet::Parser; end require_relative 'parser/ast' require_relative 'parser/abstract_compiler' require_relative 'parser/compiler' require_relative 'parser/compiler/catalog_validator' require_relative '../puppet/resource/type_collection' require_relative 'parser/functions' require_relative 'parser/files' require_relative 'parser/relationship' require_relative '../puppet/resource/type' require 'monitor' require_relative 'parser/compiler/catalog_validator/relationship_validator' # PUP-3274 This should probably go someplace else class Puppet::LexError < RuntimeError; end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/x509.rb
lib/puppet/x509.rb
# frozen_string_literal: true require_relative '../puppet' require_relative '../puppet/ssl/openssl_loader' # Responsible for loading and saving certificates and private keys. # # @see Puppet::X509::CertProvider # @api private module Puppet::X509 require_relative 'x509/pem_store' require_relative 'x509/cert_provider' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/loaders.rb
lib/puppet/loaders.rb
# frozen_string_literal: true require_relative '../puppet/concurrent/synchronized' module Puppet module Pops require_relative '../puppet/pops/loaders' module Loader require_relative '../puppet/pops/loader/typed_name' require_relative '../puppet/pops/loader/loader' require_relative '../puppet/pops/loader/base_loader' require_relative '../puppet/pops/loader/gem_support' require_relative '../puppet/pops/loader/module_loaders' require_relative '../puppet/pops/loader/dependency_loader' require_relative '../puppet/pops/loader/static_loader' require_relative '../puppet/pops/loader/runtime3_type_loader' require_relative '../puppet/pops/loader/ruby_function_instantiator' require_relative '../puppet/pops/loader/ruby_legacy_function_instantiator' require_relative '../puppet/pops/loader/ruby_data_type_instantiator' require_relative '../puppet/pops/loader/puppet_function_instantiator' require_relative '../puppet/pops/loader/type_definition_instantiator' require_relative '../puppet/pops/loader/puppet_resource_type_impl_instantiator' require_relative '../puppet/pops/loader/loader_paths' require_relative '../puppet/pops/loader/simple_environment_loader' require_relative '../puppet/pops/loader/predefined_loader' require_relative '../puppet/pops/loader/generic_plan_instantiator' require_relative '../puppet/pops/loader/puppet_plan_instantiator' end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/reports.rb
lib/puppet/reports.rb
# frozen_string_literal: true require_relative '../puppet/util/instance_loader' # This class is an implementation of a simple mechanism for loading and returning reports. # The intent is that a user registers a report by calling {register_report} and providing a code # block that performs setup, and defines a method called `process`. The setup, and the `process` method # are called in the context where `self` is an instance of {Puppet::Transaction::Report} which provides the actual # data for the report via its methods. # # @example Minimal scaffolding for a report... # Puppet::Reports::.register_report(:myreport) do # # do setup here # def process # if self.status == 'failed' # msg = "failed puppet run for #{self.host} #{self.status}" # . . . # else # . . . # end # end # end # # Required configuration: # -- # * A .rb file that defines a new report should be placed in the master's directory `lib/puppet/reports` # * The `puppet.conf` file must have `report = true` in the `[agent]` section # # @see Puppet::Transaction::Report # @api public # class Puppet::Reports extend Puppet::Util::ClassGen extend Puppet::Util::InstanceLoader # Set up autoloading and retrieving of reports. instance_load :report, 'puppet/reports' class << self # @api private attr_reader :hooks end # Adds a new report type. # The block should contain setup, and define a method with the name `process`. The `process` method is # called when the report is executed; the `process` method has access to report data via methods available # in its context where `self` is an instance of {Puppet::Transaction::Report}. # # For an example, see the overview of this class. # # @param name [Symbol] the name of the report (do not use whitespace in the name). # @param options [Hash] a hash of options # @option options [Boolean] :useyaml whether yaml should be used or not # @todo Uncertain what the options :useyaml really does; "whether yaml should be used or not", used where/how? # def self.register_report(name, options = {}, &block) name = name.intern mod = genmodule(name, :extend => Puppet::Util::Docs, :hash => instance_hash(:report), :overwrite => true, :block => block) mod.useyaml = true if options[:useyaml] mod.send(:define_method, :report_name) do name end end # Collects the docs for all reports. # @api private def self.reportdocs docs = ''.dup # Use this method so they all get loaded instance_loader(:report).loadall(Puppet.lookup(:current_environment)) loaded_instances(:report).sort_by(&:to_s).each do |name| mod = report(name) docs << "#{name}\n#{'-' * name.to_s.length}\n" docs << Puppet::Util::Docs.scrub(mod.doc) << "\n\n" end docs end # Lists each of the reports. # @api private def self.reports instance_loader(:report).loadall(Puppet.lookup(:current_environment)) loaded_instances(:report) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/etc.rb
lib/puppet/etc.rb
# frozen_string_literal: true require_relative '../puppet/util/character_encoding' # Wrapper around Ruby Etc module allowing us to manage encoding in a single # place. # This represents a subset of Ruby's Etc module, only the methods required by Puppet. # On Ruby 2.1.0 and later, Etc returns strings in variable encoding depending on # environment. The string returned will be labeled with the environment's # encoding (Encoding.default_external), with one exception: If the environment # encoding is 7-bit ASCII, and any individual character bit representation is # equal to or greater than 128 - \x80 - 0b10000000 - signifying the smallest # 8-bit big-endian value, the returned string will be in BINARY encoding instead # of environment encoding. # # Barring that exception, the returned string will be labeled as encoding # Encoding.default_external, regardless of validity or byte-width. For example, # ruby will label a string containing a four-byte characters such as "\u{2070E}" # as EUC_KR even though EUC_KR is a two-byte width encoding. # # On Ruby 2.0.x and earlier, Etc will always return string values in BINARY, # ignoring encoding altogether. # # For Puppet we specifically want UTF-8 as our input from the Etc module - which # is our input for many resource instance 'is' values. The associated 'should' # value will basically always be coming from Puppet in UTF-8 - and written to # disk as UTF-8. Etc is defined for Windows but the majority calls to it return # nil and Puppet does not use it. # # That being said, we have cause to retain the original, pre-override string # values. `puppet resource user` # (Puppet::Resource::User.indirection.search('User', {})) uses self.instances to # query for user(s) and then iterates over the results of that query again to # obtain state for each user. If we've overridden the original user name and not # retained the original, we've lost the ability to query the system for it # later. Hence the Puppet::Etc::Passwd and Puppet::Etc::Group structs. # # We only use Etc for retrieving existing property values from the system. For # setting property values, providers leverage system tools (i.e., `useradd`) # # @api private module Puppet::Etc class << self # Etc::getgrent returns an Etc::Group struct object # On first call opens /etc/group and returns parse of first entry. Each subsquent call # returns new struct the next entry or nil if EOF. Call ::endgrent to close file. def getgrent override_field_values_to_utf8(::Etc.getgrent) end # closes handle to /etc/group file def endgrent ::Etc.endgrent end # effectively equivalent to IO#rewind of /etc/group def setgrent ::Etc.setgrent end # Etc::getpwent returns an Etc::Passwd struct object # On first call opens /etc/passwd and returns parse of first entry. Each subsquent call # returns new struct for the next entry or nil if EOF. Call ::endgrent to close file. def getpwent override_field_values_to_utf8(::Etc.getpwent) end # closes handle to /etc/passwd file def endpwent ::Etc.endpwent end # effectively equivalent to IO#rewind of /etc/passwd def setpwent ::Etc.setpwent end # Etc::getpwnam searches /etc/passwd file for an entry corresponding to # username. # returns an Etc::Passwd struct corresponding to the entry or raises # ArgumentError if none def getpwnam(username) override_field_values_to_utf8(::Etc.getpwnam(username)) end # Etc::getgrnam searches /etc/group file for an entry corresponding to groupname. # returns an Etc::Group struct corresponding to the entry or raises # ArgumentError if none def getgrnam(groupname) override_field_values_to_utf8(::Etc.getgrnam(groupname)) end # Etc::getgrid searches /etc/group file for an entry corresponding to id. # returns an Etc::Group struct corresponding to the entry or raises # ArgumentError if none def getgrgid(id) override_field_values_to_utf8(::Etc.getgrgid(id)) end # Etc::getpwuid searches /etc/passwd file for an entry corresponding to id. # returns an Etc::Passwd struct corresponding to the entry or raises # ArgumentError if none def getpwuid(id) override_field_values_to_utf8(::Etc.getpwuid(id)) end # Etc::group returns a Ruby iterator that executes a block for # each entry in the /etc/group file. The code-block is passed # a Group struct. See getgrent above for more details. def group # The implementation here duplicates the logic in https://github.com/ruby/etc/blob/master/ext/etc/etc.c#L523-L537 # Note that we do not call ::Etc.group directly, because we # want to use our wrappers for methods like getgrent, setgrent, # endgrent, etc. return getgrent unless block_given? setgrent begin while cur_group = getgrent # rubocop:disable Lint/AssignmentInCondition yield cur_group end ensure endgrent end end private # @api private # Defines Puppet::Etc::Passwd struct class. Contains all of the original # member fields of Etc::Passwd, and additional "canonical_" versions of # these fields as well. API compatible with Etc::Passwd. Because Struct.new # defines a new Class object, we memoize to avoid superfluous extra Class # instantiations. # rubocop:disable Naming/MemoizedInstanceVariableName def puppet_etc_passwd_class @password_class ||= Struct.new(*Etc::Passwd.members, *Etc::Passwd.members.map { |member| "canonical_#{member}".to_sym }) end # @api private # Defines Puppet::Etc::Group struct class. Contains all of the original # member fields of Etc::Group, and additional "canonical_" versions of these # fields as well. API compatible with Etc::Group. Because Struct.new # defines a new Class object, we memoize to avoid superfluous extra Class # instantiations. def puppet_etc_group_class @group_class ||= Struct.new(*Etc::Group.members, *Etc::Group.members.map { |member| "canonical_#{member}".to_sym }) end # rubocop:enable Naming/MemoizedInstanceVariableName # Utility method for overriding the String values of a struct returned by # the Etc module to UTF-8. Structs returned by the ruby Etc module contain # members with fields of type String, Integer, or Array of Strings, so we # handle these types. Otherwise ignore fields. # # @api private # @param [Etc::Passwd or Etc::Group struct] # @return [Puppet::Etc::Passwd or Puppet::Etc::Group struct] a new struct # object with the original struct values overridden to UTF-8, if valid. For # invalid values originating in UTF-8, invalid characters are replaced with # '?'. For each member the struct also contains a corresponding # :canonical_<member name> struct member. def override_field_values_to_utf8(struct) return nil if struct.nil? new_struct = struct.is_a?(Etc::Passwd) ? puppet_etc_passwd_class.new : puppet_etc_group_class.new struct.each_pair do |member, value| case value when String new_struct["canonical_#{member}".to_sym] = value.dup new_struct[member] = Puppet::Util::CharacterEncoding.override_encoding_to_utf_8(value).scrub when Array new_struct["canonical_#{member}".to_sym] = value.inject([]) { |acc, elem| acc << elem.dup } new_struct[member] = value.inject([]) do |acc, elem| acc << Puppet::Util::CharacterEncoding.override_encoding_to_utf_8(elem).scrub end else new_struct["canonical_#{member}".to_sym] = value new_struct[member] = value end end new_struct end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/http.rb
lib/puppet/http.rb
# frozen_string_literal: true module Puppet # Contains an HTTP client for making network requests to puppet and other # HTTP servers. # # @see Puppet::HTTP::Client # @see Puppet::HTTP::HTTPError # @see Puppet::HTTP::Response # @api public module HTTP ACCEPT_ENCODING = "gzip;q=1.0,deflate;q=0.6,identity;q=0.3" HEADER_PUPPET_VERSION = "X-Puppet-Version" require_relative 'http/errors' require_relative 'http/site' require_relative 'http/pool_entry' require_relative 'http/proxy' require_relative 'http/factory' require_relative 'http/pool' require_relative 'http/dns' require_relative 'http/response' require_relative 'http/response_converter' require_relative 'http/response_net_http' require_relative 'http/service' require_relative 'http/service/ca' require_relative 'http/service/compiler' require_relative 'http/service/file_server' require_relative 'http/service/puppetserver' require_relative 'http/service/report' require_relative 'http/session' require_relative 'http/resolver' require_relative 'http/resolver/server_list' require_relative 'http/resolver/settings' require_relative 'http/resolver/srv' require_relative 'http/client' require_relative 'http/redirector' require_relative 'http/retry_after_handler' require_relative 'http/external_client' end # Legacy HTTP API module Network module HTTP require_relative '../puppet/network/http_pool' end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/confiner.rb
lib/puppet/confiner.rb
# frozen_string_literal: true require_relative '../puppet/confine_collection' # The Confiner module contains methods for managing a Provider's confinement (suitability under given # conditions). The intent is to include this module in an object where confinement management is wanted. # It lazily adds an instance variable `@confine_collection` to the object where it is included. # module Puppet::Confiner # Confines a provider to be suitable only under the given conditions. # The hash describes a confine using mapping from symbols to values or predicate code. # # * _fact_name_ => value of fact (or array of facts) # * `:exists` => the path to an existing file # * `:true` => a predicate code block returning true # * `:false` => a predicate code block returning false # * `:feature` => name of system feature that must be present # * `:any` => an array of expressions that will be ORed together # # @example # confine 'os.name' => [:redhat, :fedora] # confine :true { ... } # # @param hash [Hash<{Symbol => Object}>] hash of confines # @return [void] # @api public # def confine(hash) confine_collection.confine(hash) end # @return [Puppet::ConfineCollection] the collection of confines # @api private # def confine_collection @confine_collection ||= Puppet::ConfineCollection.new(to_s) end # Checks whether this implementation is suitable for the current platform (or returns a summary # of all confines if short == false). # @return [Boolean. Hash] Returns whether the confines are all valid (if short == true), or a hash of all confines # if short == false. # @api public # def suitable?(short = true) (short ? confine_collection.valid? : confine_collection.summary) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings.rb
lib/puppet/settings.rb
# frozen_string_literal: true require_relative '../puppet' require 'getoptlong' require_relative '../puppet/util/watched_file' require_relative '../puppet/util/command_line/puppet_option_parser' require 'forwardable' require 'fileutils' require 'concurrent' require_relative 'concurrent/lock' # The class for handling configuration files. class Puppet::Settings extend Forwardable include Enumerable require_relative 'settings/errors' require_relative 'settings/base_setting' require_relative 'settings/string_setting' require_relative 'settings/enum_setting' require_relative 'settings/symbolic_enum_setting' require_relative 'settings/array_setting' require_relative 'settings/file_setting' require_relative 'settings/directory_setting' require_relative 'settings/file_or_directory_setting' require_relative 'settings/path_setting' require_relative 'settings/boolean_setting' require_relative 'settings/integer_setting' require_relative 'settings/port_setting' require_relative 'settings/terminus_setting' require_relative 'settings/duration_setting' require_relative 'settings/ttl_setting' require_relative 'settings/priority_setting' require_relative 'settings/autosign_setting' require_relative 'settings/config_file' require_relative 'settings/value_translator' require_relative 'settings/environment_conf' require_relative 'settings/server_list_setting' require_relative 'settings/http_extra_headers_setting' require_relative 'settings/certificate_revocation_setting' require_relative 'settings/alias_setting' # local reference for convenience PuppetOptionParser = Puppet::Util::CommandLine::PuppetOptionParser attr_reader :timer # These are the settings that every app is required to specify; there are # reasonable defaults defined in application.rb. REQUIRED_APP_SETTINGS = [:logdir, :confdir, :vardir, :codedir] # The acceptable sections of the puppet.conf configuration file. ALLOWED_SECTION_NAMES = %w[main server master agent user].freeze NONE = 'none' # 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. 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 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 def self.hostname_fact Puppet.runtime[:facter].value('networking.hostname') end def self.domain_fact Puppet.runtime[:facter].value('networking.domain') end def self.default_config_file_name "puppet.conf" end 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 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 # Create a new collection of config settings. 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 # Retrieve a config value # @param param [Symbol] the name of the setting # @return [Object] the value of the setting # @api private def [](param) if @deprecated_setting_names.include?(param) issue_deprecation_warning(setting(param), "Accessing '#{param}' as a setting is deprecated.") end value(param) end # Set a config value. This doesn't set the defaults, it sets the value itself. # @param param [Symbol] the name of the setting # @param value [Object] the new value of the setting # @api private 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 # 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`. # # @param param [Symbol] the name of the setting # @param value [Object] the new default value for the setting # @api private def override_default(param, value) @value_sets[:overridden_defaults].set(param, value) unsafe_flush_cache end # Generate the list of valid arguments, in a format that GetoptLong can # understand, and add them to the passed option list. def addargs(options) # Add all of the settings as valid options. each { |_name, setting| setting.getopt_args.each { |args| options << args } } options end # Generate the list of valid arguments, in a format that OptionParser can # understand, and add them to the passed option list. def optparse_addargs(options) # Add all of the settings as valid options. each { |_name, setting| options << setting.optparse_args } options end # Is our setting a boolean setting? def boolean?(param) param = param.to_sym @config.include?(param) and @config[param].is_a?(BooleanSetting) end # Remove all set values, potentially skipping cli values. def clear unsafe_clear end # Remove all set values, potentially skipping cli values. def unsafe_clear(clear_cli = true, clear_application_defaults = false) if clear_application_defaults @value_sets[:application_defaults] = Values.new(:application_defaults, @config) @app_defaults_initialized = false end if clear_cli @value_sets[:cli] = Values.new(:cli, @config) # Only clear the 'used' values if we were explicitly asked to clear out # :cli values; otherwise, it may be just a config file reparse, # and we want to retain this cli values. @used = [] end @value_sets[:memory] = Values.new(:memory, @config) @value_sets[:overridden_defaults] = Values.new(:overridden_defaults, @config) @deprecated_settings_that_have_been_configured.clear @values.clear @cache.clear end private :unsafe_clear # 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 # # @api private def clear_environment_settings(environment) if environment.nil? return end @cache[environment.to_sym].clear @values[environment.to_sym] = {} end # 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. def flush_cache unsafe_flush_cache end def unsafe_flush_cache clearused end private :unsafe_flush_cache def clearused @cache.clear @used = [] end def global_defaults_initialized? @global_defaults_initialized end 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 # This method is called during application bootstrapping. It is responsible for parsing all of the # command line options and initializing the settings accordingly. # # It will ignore options that are not defined in the global puppet settings list, because they may # be valid options for the specific application that we are about to launch... however, at this point # in the bootstrapping lifecycle, we don't yet know what that application is. def parse_global_options(args) # Create an option parser option_parser = PuppetOptionParser.new option_parser.ignore_invalid_options = true # Add all global options to it. optparse_addargs([]).each do |option| option_parser.on(*option) do |arg| opt, val = Puppet::Settings.clean_opt(option[0], arg) handlearg(opt, val) end end option_parser.on('--run_mode', "The effective 'run mode' of the application: server, agent, or user.", :REQUIRED) do |arg| Puppet.settings.preferred_run_mode = arg end option_parser.parse(args) # remove run_mode options from the arguments so that later parses don't think # it is an unknown option. while option_index = args.index('--run_mode') # rubocop:disable Lint/AssignmentInCondition args.delete_at option_index args.delete_at option_index end args.reject! { |arg| arg.start_with? '--run_mode=' } end private :parse_global_options # 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). # # @param [String] opt the command line option that we are munging # @param [String, TrueClass, FalseClass] val the value for the setting (as determined by the OptionParser) 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 def app_defaults_initialized? @app_defaults_initialized end 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 apply_metadata call_hooks_deferred_to_application_initialization issue_deprecations REQUIRED_APP_SETTINGS.each do |key| create_ancestors(Puppet[key]) end @app_defaults_initialized = true end # Create ancestor directories. # # @param dir [String] absolute path for a required application default directory # @api private def create_ancestors(dir) parent_dir = File.dirname(dir) unless File.exist?(parent_dir) FileUtils.mkdir_p(parent_dir) end end private :create_ancestors def call_hooks_deferred_to_application_initialization(options = {}) @hooks_to_call_on_application_initialization.each do |setting| setting.handle(value(setting.name)) rescue InterpolationError => err raise InterpolationError, err.message, err.backtrace unless options[:ignore_interpolation_dependency_errors] # swallow. We're not concerned if we can't call hooks because dependencies don't exist yet # we'll get another chance after application defaults are initialized end end private :call_hooks_deferred_to_application_initialization # Return a value's description. def description(name) obj = @config[name.to_sym] if obj obj.desc else nil end end def_delegators :@config, :each, :each_pair, :each_key # Iterate over each section name. def eachsection yielded = [] @config.each_value do |object| section = object.section unless yielded.include? section yield section yielded << section end end end # Returns a given setting by name # @param name [Symbol] The name of the setting to fetch # @return [Puppet::Settings::BaseSetting] The setting object def setting(param) param = param.to_sym @config[param] end # Handle a command-line argument. 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 def include?(name) name = name.intern if name.is_a? String @config.include?(name) end # Prints the contents of a config file with the available config settings, or it # prints a single value of a config setting. 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 def generate_config puts to_config true end def generate_manifest puts to_manifest true end def print_configs return print_config_options if value(:configprint) != "" return generate_config if value(:genconfig) generate_manifest if value(:genmanifest) end def print_configs? (value(:configprint) != "" || value(:genconfig) || value(:genmanifest)) && true end # The currently configured run mode that is preferred for constructing the application configuration. def preferred_run_mode @preferred_run_mode_name || :user end # 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 # # @param mode [String|Symbol] the name of the mode to have in effect # @api private 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 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 apply_metadata end # Parse the configuration file. Just provides thread safety. def parse_config_files(require_config = true) file = which_configuration_file if Puppet::FileSystem.exist?(file) begin text = read_file(file) rescue => detail message = _("Could not load %{file}: %{detail}") % { file: file, detail: detail } if require_config Puppet.log_and_raise(detail, message) else Puppet.log_exception(detail, message) return end end else return end parse_config(text, file) end private :parse_config_files def main_config_file if explicit_config_file? self[:config] else File.join(Puppet::Util::RunMode[:server].conf_dir, config_file_name) end end private :main_config_file def user_config_file File.join(Puppet::Util::RunMode[:user].conf_dir, config_file_name) end private :user_config_file # This method is here to get around some life-cycle issues. We need to be # able to determine the config file name before the settings / defaults are # fully loaded. However, we also need to respect any overrides of this value # that the user may have specified on the command line. # # The easiest way to do this is to attempt to read the setting, and if we # catch an error (meaning that it hasn't been set yet), we'll fall back to # the default value. def config_file_name begin return self[:config_file_name] if self[:config_file_name] rescue SettingsError # This just means that the setting wasn't explicitly set on the command line, so we will ignore it and # fall through to the default name. end self.class.default_config_file_name end private :config_file_name def apply_metadata # We have to do it in the reverse of the search path, # because multiple sections could set the same value # and I'm too lazy to only set the metadata once. if @configuration_file searchpath(nil, preferred_run_mode).reverse_each do |source| section = @configuration_file.sections[source.name] if source.type == :section if section apply_metadata_from_section(section) end end end end private :apply_metadata def apply_metadata_from_section(section) section.settings.each do |setting| type = @config[setting.name] if setting.has_metadata? if type type.set_meta(setting.meta) end end end 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 } # Create a new setting. The value is passed in because it's used to determine # what kind of setting we're creating, but the value itself might be either # a default or a value, so we can't actually assign it. # # See #define_settings for documentation on the legal values for the ":type" option. def newsetting(hash) klass = nil hash[:section] = hash[:section].to_sym if hash[:section] type = hash[:type] if type klass = SETTING_TYPES[type] unless klass raise ArgumentError, _("Invalid setting type '%{type}'") % { type: type } end hash.delete(:type) else # The only implicit typing we still do for settings is to fall back to "String" type if they didn't explicitly # specify a type. Personally I'd like to get rid of this too, and make the "type" option mandatory... but # there was a little resistance to taking things quite that far for now. --cprice 2012-03-19 klass = StringSetting end hash[:settings] = self klass.new(hash) end # This has to be private, because it doesn't add the settings to @config private :newsetting # Iterate across all of the objects in a given section. def persection(section) section = section.to_sym each { |_name, obj| if obj.section == section yield obj end } end # Reparse our config file, if necessary. 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 def files return @files if @files @files = [] [main_config_file, user_config_file].each do |path| if Puppet::FileSystem.exist?(path) @files << Puppet::Util::WatchedFile.new(path) end end @files end private :files # Checks to see if any of the config files have been modified # @return the filename of the first file that is found to have changed, or # nil if no files have changed def any_files_changed? files.each do |file| return file.to_str if file.changed? end nil end private :any_files_changed? def reuse return unless defined?(@used) new = @used @used = [] use(*new) end SearchPathElement = Struct.new(:name, :type) # The order in which to search for values, without defaults. # # @param environment [String,Symbol] symbolic reference to an environment name # @param run_mode [Symbol] symbolic reference to a Puppet run mode # @return [Array<SearchPathElement>] # @api private 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 # The order in which to search for values. # # @param environment [String,Symbol] symbolic reference to an environment name # @param run_mode [Symbol] symbolic reference to a Puppet run mode # @return [Array<SearchPathElement>] # @api private 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 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 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 # 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 # # @param param [String, Symbol] the setting to look up # @return [Object, nil] the value of the setting or nil if unset def set_by_cli(param) param = param.to_sym @value_sets[:cli].lookup(param) end def set_by_cli?(param) !!set_by_cli(param) end # Get values from a search path entry. # @api private 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 # Allow later inspection to determine if the setting was set by user # config, rather than a default setting. 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 # Allow later inspection to determine if the setting was set in a specific # section # # @param param [String, Symbol] the setting to look up # @param section [Symbol] the section in which to look up the setting # @return [Object, nil] the value of the setting or nil if unset def set_in_section(param, section) param = param.to_sym vals = searchpath_values(SearchPathElement.new(section, :section)) if vals vals.lookup(param) end end def set_in_section?(param, section) !!set_in_section(param, section) end # 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. # @api private # def patch_value(param, value, type) if @value_sets[type] @value_sets[type].set(param, value) unsafe_flush_cache end end # Define a group of settings. # # @param [Symbol] section 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. # @param [Hash[Hash]] defs 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:
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face.rb
lib/puppet/face.rb
# frozen_string_literal: true # The public name of this feature is 'face', but we have hidden all the # plumbing over in the 'interfaces' namespace to make clear the distinction # between the two. # # This file exists to ensure that the public name is usable without revealing # the details of the implementation; you really only need go look at anything # under Interfaces if you are looking to extend the implementation. # # It isn't hidden to gratuitously hide things, just to make it easier to # separate out the interests people will have. --daniel 2011-04-07 require_relative '../puppet/interface' Puppet::Face = Puppet::Interface
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/concurrent.rb
lib/puppet/concurrent.rb
# frozen_string_literal: true module Puppet::Concurrent end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/property.rb
lib/puppet/property.rb
# frozen_string_literal: true # The virtual base class for properties, which are the self-contained building # blocks for actually doing work on the system. require_relative '../puppet' require_relative '../puppet/parameter' # The Property class is the implementation of a resource's attributes of _property_ kind. # A Property is a specialized Resource Type Parameter that has both an 'is' (current) state, and # a 'should' (wanted state). However, even if this is conceptually true, the current _is_ value is # obtained by asking the associated provider for the value, and hence it is not actually part of a # property's state, and only available when a provider has been selected and can obtain the value (i.e. when # running on an agent). # # A Property (also in contrast to a parameter) is intended to describe a managed attribute of # some system entity, such as the name or mode of a file. # # The current value _(is)_ is read and written with the methods {#retrieve} and {#set}, and the wanted # value _(should)_ is read and written with the methods {#value} and {#value=} which delegate to # {#should} and {#should=}, i.e. when a property is used like any other parameter, it is the _should_ value # that is operated on. # # All resource type properties in the puppet system are derived from this class. # # The intention is that new parameters are created by using the DSL method {Puppet::Type.newproperty}. # # @abstract # @note Properties of Types are expressed using subclasses of this class. Such a class describes one # named property of a particular Type (as opposed to describing a type of property in general). This # limits the use of one (concrete) property class instance to occur only once for a given type's inheritance # chain. An instance of a Property class is the value holder of one instance of the resource type (e.g. the # mode of a file resource instance). # A Property class may server as the superclass _(parent)_ of another; e.g. a Size property that describes # handling of measurements such as kb, mb, gb. If a type requires two different size measurements it requires # one concrete class per such measure; e.g. MinSize (:parent => Size), and MaxSize (:parent => Size). # # @see Puppet::Type # @see Puppet::Parameter # # @api public # class Puppet::Property < Puppet::Parameter require_relative 'property/ensure' # Returns the original wanted value(s) _(should)_ unprocessed by munging/unmunging. # The original values are set by {#value=} or {#should=}. # @return (see #should) # attr_reader :shouldorig # The noop mode for this property. # By setting a property's noop mode to `true`, any management of this property is inhibited. Calculation # and reporting still takes place, but if a change of the underlying managed entity's state # should take place it will not be carried out. This noop # setting overrides the overall `Puppet[:noop]` mode as well as the noop mode in the _associated resource_ # attr_writer :noop class << self # @todo Figure out what this is used for. Can not find any logic in the puppet code base that # reads or writes this attribute. # ??? Probably Unused attr_accessor :unmanaged # @return [Symbol] The name of the property as given when the property was created. # attr_reader :name # @!attribute [rw] array_matching # @comment note that $#46; is a period - char code require to not terminate sentence. # The `is` vs&#46; `should` array matching mode; `:first`, or `:all`. # # @comment there are two blank chars after the symbols to cause a break - do not remove these. # * `:first` # This is primarily used for single value properties. When matched against an array of values # a match is true if the `is` value matches any of the values in the `should` array. When the `is` value # is also an array, the matching is performed against the entire array as the `is` value. # * `:all` # : This is primarily used for multi-valued properties. When matched against an array of # `should` values, the size of `is` and `should` must be the same, and all values in `is` must match # a value in `should`. # # @note The semantics of these modes are implemented by the method {#insync?}. That method is the default # implementation and it has a backwards compatible behavior that imposes additional constraints # on what constitutes a positive match. A derived property may override that method. # @return [Symbol] (:first) the mode in which matching is performed # @see #insync? # @dsl type # @api public # def array_matching @array_matching ||= :first end # @comment This is documented as an attribute - see the {array_matching} method. # def array_matching=(value) value = value.intern if value.is_a?(String) # TRANSLATORS 'Property#array_matching', 'first', and 'all' should not be translated raise ArgumentError, _("Supported values for Property#array_matching are 'first' and 'all'") unless [:first, :all].include?(value) @array_matching = value end # Used to mark a type property as having or lacking idempotency (on purpose # generally). This is used to avoid marking the property as a # corrective_change when there is known idempotency issues with the property # rendering a corrective_change flag as useless. # @return [Boolean] true if the property is marked as idempotent def idempotent @idempotent.nil? ? @idempotent = true : @idempotent end # Attribute setter for the idempotent attribute. # @param [bool] value boolean indicating if the property is idempotent. # @see idempotent def idempotent=(value) @idempotent = value end end # Looks up a value's name among valid values, to enable option lookup with result as a key. # @param name [Object] the parameter value to match against valid values (names). # @return {Symbol, Regexp} a value matching predicate # @api private # def self.value_name(name) value = value_collection.match?(name) value.name if value end # Returns the value of the given option (set when a valid value with the given "name" was defined). # @param name [Symbol, Regexp] the valid value predicate as returned by {value_name} # @param option [Symbol] the name of the wanted option # @return [Object] value of the option # @raise [NoMethodError] if the option is not supported # @todo Guessing on result of passing a non supported option (it performs send(option)). # @api private # def self.value_option(name, option) value = value_collection.value(name) value.send(option) if value end # Defines a new valid value for this property. # A valid value is specified as a literal (typically a Symbol), but can also be # specified with a Regexp. # # @param name [Symbol, Regexp] a valid literal value, or a regexp that matches a value # @param options [Hash] a hash with options # @option options [Symbol] :event The event that should be emitted when this value is set. # @todo Option :event original comment says "event should be returned...", is "returned" the correct word # to use? # @option options [Symbol] :invalidate_refreshes Indicates a change on this property should invalidate and # remove any scheduled refreshes (from notify or subscribe) targeted at the same resource. For example, if # a change in this property takes into account any changes that a scheduled refresh would have performed, # then the scheduled refresh would be deleted. # @option options [Object] any Any other option is treated as a call to a setter having the given # option name (e.g. `:required_features` calls `required_features=` with the option's value as an # argument). # # @dsl type # @api public def self.newvalue(name, options = {}, &block) value = value_collection.newvalue(name, options, &block) unless value.method.nil? method = value.method.to_sym if value.block if instance_methods(false).include?(method) raise ArgumentError, _("Attempt to redefine method %{method} with block") % { method: method } end define_method(method, &value.block) else # Let the method be an alias for calling the providers setter unless we already have this method alias_method(method, :call_provider) unless method_defined?(method) end end value end # Calls the provider setter method for this property with the given value as argument. # @return [Object] what the provider returns when calling a setter for this property's name # @raise [Puppet::Error] when the provider can not handle this property. # @see #set # @api private # def call_provider(value) # We have no idea how to handle this unless our parent have a provider self.fail "#{self.class.name} cannot handle values of type #{value.inspect}" unless @resource.provider method = self.class.name.to_s + "=" unless provider.respond_to? method self.fail "The #{provider.class.name} provider can not handle attribute #{self.class.name}" end provider.send(method, value) end # Formats a message for a property change from the given `current_value` to the given `newvalue`. # @return [String] a message describing the property change. # @note If called with equal values, this is reported as a change. # @raise [Puppet::DevError] if there were issues formatting the message # def change_to_s(current_value, newvalue) if current_value == :absent "defined '#{name}' as #{should_to_s(newvalue)}" elsif newvalue == :absent or newvalue == [:absent] "undefined '#{name}' from #{is_to_s(current_value)}" else "#{name} changed #{is_to_s(current_value)} to #{should_to_s(newvalue)}" end rescue Puppet::Error raise rescue => detail message = _("Could not convert change '%{name}' to string: %{detail}") % { name: name, detail: detail } Puppet.log_exception(detail, message) raise Puppet::DevError, message, detail.backtrace end # Produces the name of the event to use to describe a change of this property's value. # The produced event name is either the event name configured for this property, or a generic # event based on the name of the property with suffix `_changed`, or if the property is # `:ensure`, the name of the resource type and one of the suffixes `_created`, `_removed`, or `_changed`. # @return [String] the name of the event that describes the change # def event_name value = should event_name = self.class.value_option(value, :event) and return event_name name == :ensure or return (name.to_s + "_changed").to_sym (resource.type.to_s + case value when :present; "_created" when :absent; "_removed" else "_changed" end).to_sym end # Produces an event describing a change of this property. # In addition to the event attributes set by the resource type, this method adds: # # * `:name` - the event_name # * `:desired_value` - a.k.a _should_ or _wanted value_ # * `:property` - reference to this property # * `:source_description` - The containment path of this property, indicating what resource this # property is associated with and in what stage and class that resource # was declared, e.g. "/Stage[main]/Myclass/File[/tmp/example]/ensure" # * `:invalidate_refreshes` - if scheduled refreshes should be invalidated # * `:redacted` - if the event will be redacted (due to this property being sensitive) # # @return [Puppet::Transaction::Event] the created event # @see Puppet::Type#event def event(options = {}) attrs = { :name => event_name, :desired_value => should, :property => self, :source_description => path }.merge(options) value = self.class.value_collection.match?(should) if should attrs[:invalidate_refreshes] = true if value && value.invalidate_refreshes attrs[:redacted] = @sensitive resource.event attrs end # Determines whether the property is in-sync or not in a way that is protected against missing value. # @note If the wanted value _(should)_ is not defined or is set to a non-true value then this is # a state that can not be fixed and the property is reported to be in sync. # @return [Boolean] the protected result of `true` or the result of calling {#insync?}. # # @api private # @note Do not override this method. # def safe_insync?(is) # If there is no @should value, consider the property to be in sync. return true unless @should # Otherwise delegate to the (possibly derived) insync? method. insync?(is) end # Protects against override of the {#safe_insync?} method. # @raise [RuntimeError] if the added method is `:safe_insync?` # @api private # def self.method_added(sym) raise "Puppet::Property#safe_insync? shouldn't be overridden; please override insync? instead" if sym == :safe_insync? end # Checks if the current _(is)_ value is in sync with the wanted _(should)_ value. # The check if the two values are in sync is controlled by the result of {#match_all?} which # specifies a match of `:first` or `:all`). The matching of the _is_ value against the entire _should_ value # or each of the _should_ values (as controlled by {#match_all?} is performed by {#property_matches?}. # # A derived property typically only needs to override the {#property_matches?} method, but may also # override this method if there is a need to have more control over the array matching logic. # # @note The array matching logic in this method contains backwards compatible logic that performs the # comparison in `:all` mode by checking equality and equality of _is_ against _should_ converted to array of String, # and that the lengths are equal, and in `:first` mode by checking if one of the _should_ values # is included in the _is_ values. This means that the _is_ value needs to be carefully arranged to # match the _should_. # @todo The implementation should really do return is.zip(@should).all? {|a, b| property_matches?(a, b) } # instead of using equality check and then check against an array with converted strings. # @param is [Object] The current _(is)_ value to check if it is in sync with the wanted _(should)_ value(s) # @return [Boolean] whether the values are in sync or not. # @raise [Puppet::DevError] if wanted value _(should)_ is not an array. # @api public # def insync?(is) devfail "#{self.class.name}'s should is not array" unless @should.is_a?(Array) # an empty array is analogous to no should values return true if @should.empty? # Look for a matching value, either for all the @should values, or any of # them, depending on the configuration of this property. if match_all? then # Emulate Array#== using our own comparison function. # A non-array was not equal to an array, which @should always is. return false unless is.is_a? Array # If they were different lengths, they are not equal. return false unless is.length == @should.length # Finally, are all the elements equal? In order to preserve the # behaviour of previous 2.7.x releases, we need to impose some fun rules # on "equality" here. # # Specifically, we need to implement *this* comparison: the two arrays # are identical if the is values are == the should values, or if the is # values are == the should values, stringified. # # This does mean that property equality is not commutative, and will not # work unless the `is` value is carefully arranged to match the should. (is == @should or is == @should.map(&:to_s)) # When we stop being idiots about this, and actually have meaningful # semantics, this version is the thing we actually want to do. # # return is.zip(@should).all? {|a, b| property_matches?(a, b) } else @should.any? { |want| property_matches?(is, want) } end end # This method tests if two values are insync? outside of the properties current # should value. This works around the requirement for corrective_change analysis # that requires two older values to be compared with the properties potentially # custom insync? code. # # @param [Object] should the value it should be # @param [Object] is the value it is # @return [Boolean] whether or not the values are in sync or not # @api private def insync_values?(should, is) # Here be dragons. We're setting the should value of a property purely just to # call its insync? method, as it lacks a way to pass in a should. # Unfortunately there isn't an API compatible way of avoiding this, as both should # an insync? behaviours are part of the public API. Future API work should factor # this kind of arbitrary comparisons into the API to remove this complexity. -ken # Backup old should, set it to the new value, then call insync? on the property. old_should = @should begin @should = should insync?(is) rescue # Certain operations may fail, but we don't want to fail the transaction if we can # avoid it # TRANSLATORS 'insync_values?' should not be translated msg = _("Unknown failure using insync_values? on type: %{type} / property: %{name} to compare values %{should} and %{is}") % { type: resource.ref, name: name, should: should, is: is } Puppet.info(msg) # Return nil, ie. unknown nil ensure # Always restore old should @should = old_should end end # Checks if the given current and desired values are equal. # This default implementation performs this check in a backwards compatible way where # the equality of the two values is checked, and then the equality of current with desired # converted to a string. # # A derived implementation may override this method to perform a property specific equality check. # # The intent of this method is to provide an equality check suitable for checking if the property # value is in sync or not. It is typically called from {#insync?}. # def property_matches?(current, desired) # This preserves the older Puppet behaviour of doing raw and string # equality comparisons for all equality. I am not clear this is globally # desirable, but at least it is not a breaking change. --daniel 2011-11-11 current == desired or current == desired.to_s end # Produces a pretty printing string for the given value. # This default implementation calls {#format_value_for_display} on the class. A derived # implementation may perform property specific pretty printing when the _is_ values # are not already in suitable form. # @param value [Object] the value to format as a string # @return [String] a pretty printing string def is_to_s(value) # rubocop:disable Naming/PredicateName self.class.format_value_for_display(value) end # Emits a log message at the log level specified for the associated resource. # The log entry is associated with this property. # @param msg [String] the message to log # @return [void] # def log(msg) Puppet::Util::Log.create( :level => resource[:loglevel], :message => msg, :source => self ) end # @return [Boolean] whether the {array_matching} mode is set to `:all` or not def match_all? self.class.array_matching == :all end # @return [Boolean] whether the property is marked as idempotent for the purposes # of calculating corrective change. def idempotent? self.class.idempotent end # @return [Symbol] the name of the property as stated when the property was created. # @note A property class (just like a parameter class) describes one specific property and # can only be used once within one type's inheritance chain. def name self.class.name end # @return [Boolean] whether this property is in noop mode or not. # Returns whether this property is in noop mode or not; if a difference between the # _is_ and _should_ values should be acted on or not. # The noop mode is a transitive setting. The mode is checked in this property, then in # the _associated resource_ and finally in Puppet[:noop]. # @todo This logic is different than Parameter#noop in that the resource noop mode overrides # the property's mode - in parameter it is the other way around. Bug or feature? # def noop # This is only here to make testing easier. if @resource.respond_to?(:noop?) @resource.noop? elsif defined?(@noop) @noop else Puppet[:noop] end end # Retrieves the current value _(is)_ of this property from the provider. # This implementation performs this operation by calling a provider method with the # same name as this property (i.e. if the property name is 'gid', a call to the # 'provider.gid' is expected to return the current value. # @return [Object] what the provider returns as the current value of the property # def retrieve provider.send(self.class.name) end # Sets the current _(is)_ value of this property. # The _name_ associated with the value is first obtained by calling {value_name}. A dynamically created setter # method associated with this _name_ is called if it exists, otherwise the value is set using using the provider's # setter method for this property by calling ({#call_provider}). # # @param value [Object] the value to set # @return [Object] returns the result of calling the setter method or {#call_provider} # @raise [Puppet::Error] if there were problems setting the value using the setter method or when the provider # setter should be used but there is no provider in the associated resource_ # @raise [Puppet::ResourceError] if there was a problem setting the value and it was not raised # as a Puppet::Error. The original exception is wrapped and logged. # @api public # def set(value) # Set a name for looking up associated options like the event. name = self.class.value_name(value) method = self.class.value_option(name, :method) if method && respond_to?(method) begin send(method) rescue Puppet::Error raise rescue => detail error = Puppet::ResourceError.new(_("Could not set '%{value}' on %{class_name}: %{detail}") % { value: value, class_name: self.class.name, detail: detail }, @resource.file, @resource.line, detail) error.set_backtrace detail.backtrace Puppet.log_exception(detail, error.message) raise error end else block = self.class.value_option(name, :block) if block # FIXME It'd be better here to define a method, so that # the blocks could return values. instance_eval(&block) else call_provider(value) end end end # Returns the wanted _(should)_ value of this property. # If the _array matching mode_ {#match_all?} is true, an array of the wanted values in unmunged format # is returned, else the first value in the array of wanted values in unmunged format is returned. # @return [Array<Object>, Object, nil] Array of values if {#match_all?} else a single value, or nil if there are no # wanted values. # @raise [Puppet::DevError] if the wanted value is non nil and not an array # # @note This method will potentially return different values than the original values as they are # converted via munging/unmunging. If the original values are wanted, call {#shouldorig}. # # @see #shouldorig # @api public # def should return nil unless defined?(@should) devfail "should for #{self.class.name} on #{resource.name} is not an array" unless @should.is_a?(Array) if match_all? @should.collect { |val| unmunge(val) } else unmunge(@should[0]) end end # Sets the wanted _(should)_ value of this property. # If the given value is not already an Array, it will be wrapped in one before being set. # This method also sets the cached original _should_ values returned by {#shouldorig}. # # @param values [Array<Object>, Object] the value(s) to set as the wanted value(s) # @raise [StandardError] when validation of a value fails (see {#validate}). # @api public # def should=(values) values = [values] unless values.is_a?(Array) @shouldorig = values values.each { |val| validate(val) } @should = values.collect { |val| munge(val) } end # Produces a pretty printing string for the given value. # This default implementation calls {#format_value_for_display} on the class. A derived # implementation may perform property specific pretty printing when the _should_ values # are not already in suitable form. # @param value [Object] the value to format as a string # @return [String] a pretty printing string def should_to_s(value) self.class.format_value_for_display(value) end # Synchronizes the current value _(is)_ and the wanted value _(should)_ by calling {#set}. # @raise [Puppet::DevError] if {#should} is nil # @todo The implementation of this method is somewhat inefficient as it computes the should # array twice. def sync devfail "Got a nil value for should" unless should set(should) end # Asserts that the given value is valid. # If the developer uses a 'validate' hook, this method will get overridden. # @raise [Exception] if the value is invalid, or value can not be handled. # @return [void] # @api private # def unsafe_validate(value) super validate_features_per_value(value) end # Asserts that all required provider features are present for the given property value. # @raise [ArgumentError] if a required feature is not present # @return [void] # @api private # def validate_features_per_value(value) features = self.class.value_option(self.class.value_name(value), :required_features) if features features = Array(features) needed_features = features.collect(&:to_s).join(", ") unless provider.satisfies?(features) # TRANSLATORS 'Provider' refers to a Puppet provider class raise ArgumentError, _("Provider %{provider} must have features '%{needed_features}' to set '%{property}' to '%{value}'") % { provider: provider.class.name, needed_features: needed_features, property: self.class.name, value: value } end end end # @return [Object, nil] Returns the wanted _(should)_ value of this property. def value should end # (see #should=) def value=(values) self.should = values end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/runtime.rb
lib/puppet/runtime.rb
# frozen_string_literal: true require_relative '../puppet/http' require_relative '../puppet/facter_impl' require 'singleton' # Provides access to runtime implementations. # # @api private class Puppet::Runtime include Singleton def initialize @runtime_services = { http: proc do klass = Puppet::Network::HttpPool.http_client_class if klass == Puppet::Network::HTTP::Connection Puppet::HTTP::Client.new else Puppet::HTTP::ExternalClient.new(klass) end end, facter: proc { Puppet::FacterImpl.new } } end private :initialize # Loads all runtime implementations. # # @return Array[Symbol] the names of loaded implementations # @api private def load_services @runtime_services.keys.each { |key| self[key] } end # Get a runtime implementation. # # @param name [Symbol] the name of the implementation # @return [Object] the runtime implementation # @api private def [](name) service = @runtime_services[name] raise ArgumentError, "Unknown service #{name}" unless service if service.is_a?(Proc) @runtime_services[name] = service.call else service end end # Register a runtime implementation. # # @param name [Symbol] the name of the implementation # @param impl [Object] the runtime implementation # @api private def []=(name, impl) @runtime_services[name] = impl end # Clears all implementations. This is used for testing. # # @api private def clear initialize end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/facter_impl.rb
lib/puppet/facter_impl.rb
# frozen_string_literal: true # # @api private # Default Facter implementation that delegates to Facter API # module Puppet class FacterImpl def initialize require 'facter' setup_logging end def value(fact_name) ::Facter.value(fact_name) end def add(name, &block) ::Facter.add(name, &block) end def to_hash ::Facter.to_hash end def clear ::Facter.clear end def reset ::Facter.reset end def resolve(options) ::Facter.resolve(options) end def search_external(dirs) ::Facter.search_external(dirs) end def search(*dirs) ::Facter.search(*dirs) end def trace(value) ::Facter.trace(value) if ::Facter.respond_to? :trace end def debugging(value) ::Facter.debugging(value) if ::Facter.respond_to?(:debugging) end def load_external? ::Facter.respond_to?(:load_external) end def load_external(value) ::Facter.load_external(value) if load_external? end private def setup_logging return unless ::Facter.respond_to? :on_message ::Facter.on_message do |level, message| case level when :trace, :debug level = :debug when :info # Same as Puppet when :warn level = :warning when :error level = :err when :fatal level = :crit else next end Puppet::Util::Log.create( { :level => level, :source => 'Facter', :message => message } ) nil end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_system.rb
lib/puppet/file_system.rb
# frozen_string_literal: true module Puppet::FileSystem require_relative '../puppet/util' require_relative 'file_system/path_pattern' require_relative 'file_system/file_impl' require_relative 'file_system/memory_file' require_relative 'file_system/memory_impl' require_relative 'file_system/uniquefile' # create instance of the file system implementation to use for the current platform @impl = if Puppet::Util::Platform.windows? require_relative 'file_system/windows' Puppet::FileSystem::Windows elsif Puppet::Util::Platform.jruby? require_relative 'file_system/jruby' Puppet::FileSystem::JRuby else require_relative 'file_system/posix' Puppet::FileSystem::Posix end.new() # Allows overriding the filesystem for the duration of the given block. # The filesystem will only contain the given file(s). # # @param files [Puppet::FileSystem::MemoryFile] the files to have available # # @api private # def self.overlay(*files, &block) old_impl = @impl @impl = Puppet::FileSystem::MemoryImpl.new(*files) yield ensure @impl = old_impl end # Opens the given path with given mode, and options and optionally yields it to the given block. # # @param path [String, Pathname] the path to the file to operate on # @param mode [Integer] The mode to apply to the file if it is created # @param options [String] Extra file operation mode information to use # This is the standard mechanism Ruby uses in the IO class, and therefore # encoding may be specified explicitly as fmode : encoding or fmode : "BOM|UTF-*" # for example, a:ASCII or w+:UTF-8 # @yield The file handle, in the mode given by options, else read-write mode # @return [Void] # # @api public # def self.open(path, mode, options, &block) @impl.open(assert_path(path), mode, options, &block) end # @return [Object] The directory of this file as an opaque handle # # @api public # def self.dir(path) @impl.dir(assert_path(path)) end # @return [String] The directory of this file as a String # # @api public # def self.dir_string(path) @impl.path_string(@impl.dir(assert_path(path))) end # @return [Boolean] Does the directory of the given path exist? def self.dir_exist?(path) @impl.exist?(@impl.dir(assert_path(path))) end # Creates all directories down to (inclusive) the dir of the given path def self.dir_mkpath(path) @impl.mkpath(@impl.dir(assert_path(path))) end # @return [Object] the name of the file as a opaque handle # # @api public # def self.basename(path) @impl.basename(assert_path(path)) end # @return [String] the name of the file # # @api public # def self.basename_string(path) @impl.path_string(@impl.basename(assert_path(path))) end # Allows exclusive updates to a file to be made by excluding concurrent # access using flock. This means that if the file is on a filesystem that # does not support flock, this method will provide no protection. # # While polling to acquire the lock the process will wait ever increasing # amounts of time in order to prevent multiple processes from wasting # resources. # # @param path [Pathname] the path to the file to operate on # @param mode [Integer] The mode to apply to the file if it is created # @param options [String] Extra file operation mode information to use # (defaults to read-only mode 'r') # This is the standard mechanism Ruby uses in the IO class, and therefore # encoding may be specified explicitly as fmode : encoding or fmode : "BOM|UTF-*" # for example, a:ASCII or w+:UTF-8 # @param timeout [Integer] Number of seconds to wait for the lock (defaults to 300) # @yield The file handle, in the mode given by options, else read-write mode # @return [Void] # @raise [Timeout::Error] If the timeout is exceeded while waiting to acquire the lock # # @api public # def self.exclusive_open(path, mode, options = 'r', timeout = 300, &block) @impl.exclusive_open(assert_path(path), mode, options, timeout, &block) end # Processes each line of the file by yielding it to the given block # # @api public # def self.each_line(path, &block) @impl.each_line(assert_path(path), &block) end # @return [String] The contents of the file # # @api public # def self.read(path, opts = {}) @impl.read(assert_path(path), opts) end # Read a file keeping the original line endings intact. This # attempts to open files using binary mode using some encoding # overrides and falling back to IO.read when none of the # encodings are valid. # # @return [String] The contents of the file # # @api public # def self.read_preserve_line_endings(path) @impl.read_preserve_line_endings(assert_path(path)) end # @return [String] The binary contents of the file # # @api public # def self.binread(path) @impl.binread(assert_path(path)) end # Determines if a file exists by verifying that the file can be stat'd. # Will follow symlinks and verify that the actual target path exists. # # @return [Boolean] true if the named file exists. # # @api public # def self.exist?(path) @impl.exist?(assert_path(path)) end # Determines if a file is a directory. # # @return [Boolean] true if the given file is a directory. # # @api public def self.directory?(path) @impl.directory?(assert_path(path)) end # Determines if a file is a file. # # @return [Boolean] true if the given file is a file. # # @api public def self.file?(path) @impl.file?(assert_path(path)) end # Determines if a file is executable. # # @todo Should this take into account extensions on the windows platform? # # @return [Boolean] true if this file can be executed # # @api public # def self.executable?(path) @impl.executable?(assert_path(path)) end # @return [Boolean] Whether the file is writable by the current process # # @api public # def self.writable?(path) @impl.writable?(assert_path(path)) end # Touches the file. On most systems this updates the mtime of the file. # # @param mtime [Time] The last modified time or nil to use the current time # # @api public # def self.touch(path, mtime: nil) @impl.touch(assert_path(path), mtime: mtime) end # Creates directories for all parts of the given path. # # @api public # def self.mkpath(path) @impl.mkpath(assert_path(path)) end # @return [Array<Object>] references to all of the children of the given # directory path, excluding `.` and `..`. # @api public def self.children(path) @impl.children(assert_path(path)) end # Creates a symbolic link dest which points to the current file. # If dest already exists: # # * and is a file, will raise Errno::EEXIST # * and is a directory, will return 0 but perform no action # * and is a symlink referencing a file, will raise Errno::EEXIST # * and is a symlink referencing a directory, will return 0 but perform no action # # With the :force option set to true, when dest already exists: # # * and is a file, will replace the existing file with a symlink (DANGEROUS) # * and is a directory, will return 0 but perform no action # * and is a symlink referencing a file, will modify the existing symlink # * and is a symlink referencing a directory, will return 0 but perform no action # # @param dest [String] The path to create the new symlink at # @param [Hash] options the options to create the symlink with # @option options [Boolean] :force overwrite dest # @option options [Boolean] :noop do not perform the operation # @option options [Boolean] :verbose verbose output # # @raise [Errno::EEXIST] dest already exists as a file and, :force is not set # # @return [Integer] 0 # # @api public # def self.symlink(path, dest, options = {}) @impl.symlink(assert_path(path), dest, options) end # @return [Boolean] true if the file is a symbolic link. # # @api public # def self.symlink?(path) @impl.symlink?(assert_path(path)) end # @return [String] the name of the file referenced by the given link. # # @api public # def self.readlink(path) @impl.readlink(assert_path(path)) end # Deletes the given paths, returning the number of names passed as arguments. # See also Dir::rmdir. # # @raise an exception on any error. # # @return [Integer] the number of paths passed as arguments # # @api public # def self.unlink(*paths) @impl.unlink(*(paths.map { |p| assert_path(p) })) end # @return [File::Stat] object for the named file. # # @api public # def self.stat(path) @impl.stat(assert_path(path)) end # @return [Integer] the size of the file # # @api public # def self.size(path) @impl.size(assert_path(path)) end # @return [File::Stat] Same as stat, but does not follow the last symbolic # link. Instead, reports on the link itself. # # @api public # def self.lstat(path) @impl.lstat(assert_path(path)) end # Compares the contents of this file against the contents of a stream. # # @param stream [IO] The stream to compare the contents against # @return [Boolean] Whether the contents were the same # # @api public # def self.compare_stream(path, stream) @impl.compare_stream(assert_path(path), stream) end # Produces an opaque pathname "handle" object representing the given path. # Different implementations of the underlying file system may use different runtime # objects. The produced "handle" should be used in all other operations # that take a "path". No operation should be directly invoked on the returned opaque object # # @param path [String] The string representation of the path # @return [Object] An opaque path handle on which no operations should be directly performed # # @api public # def self.pathname(path) @impl.pathname(path) end # Produces a string representation of the opaque path handle, with expansions # performed on ~. For Windows, this means that C:\Users\Admini~1\AppData will # be expanded to C:\Users\Administrator\AppData. On POSIX filesystems, the # value ~ will be expanded to something like /Users/Foo # # This method exists primarlily to resolve a Ruby deficiency where # File.expand_path doesn't convert short paths to long paths, which is # important when resolving the path to load. # # @param path [Object] a path handle produced by {#pathname} # @return [String] a string representation of the path # def self.expand_path(path, dir_string = nil) @impl.expand_path(path, dir_string) end # Asserts that the given path is of the expected type produced by #pathname # # @raise [ArgumentError] when path is not of the expected type # # @api public # def self.assert_path(path) @impl.assert_path(path) end # Produces a string representation of the opaque path handle. # # @param path [Object] a path handle produced by {#pathname} # @return [String] a string representation of the path # def self.path_string(path) @impl.path_string(path) end # Create and open a file for write only if it doesn't exist. # # @see Puppet::FileSystem::open # # @raise [Errno::EEXIST] path already exists. # # @api public # def self.exclusive_create(path, mode, &block) @impl.exclusive_create(assert_path(path), mode, &block) end # Changes permission bits on the named path to the bit pattern represented # by mode. # # @param mode [Integer] The mode to apply to the file if it is created # @param path [String] The path to the file, can also accept [PathName] # # @raise [Errno::ENOENT]: path doesn't exist # # @api public # def self.chmod(mode, path) @impl.chmod(mode, assert_path(path)) end # Replace the contents of a file atomically, creating the file if necessary. # If a `mode` is specified, then it will always be applied to the file. If # a `mode` is not specified and the file exists, its mode will be preserved. # If the file doesn't exist, the mode will be set to a platform-specific # default. # # @param path [String] The path to the file, can also accept [PathName] # @param mode [Integer] Optional mode for the file. # # @raise [Errno::EISDIR]: path is a directory # # @api public # def self.replace_file(path, mode = nil, &block) @impl.replace_file(assert_path(path), mode, &block) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/thread_local.rb
lib/puppet/thread_local.rb
# frozen_string_literal: true require 'concurrent' class Puppet::ThreadLocal < Concurrent::ThreadLocalVar end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/environments.rb
lib/puppet/environments.rb
# frozen_string_literal: true require_relative '../puppet/concurrent/synchronized' # @api private module Puppet::Environments class EnvironmentNotFound < Puppet::Error def initialize(environment_name, original = nil) environmentpath = Puppet[:environmentpath] super("Could not find a directory environment named '#{environment_name}' anywhere in the path: #{environmentpath}. Does the directory exist?", original) end end # @api private module EnvironmentCreator # Create an anonymous environment. # # @param module_path [String] A list of module directories separated by the # PATH_SEPARATOR # @param manifest [String] The path to the manifest # @return A new environment with the `name` `:anonymous` # # @api private def for(module_path, manifest) Puppet::Node::Environment.create(:anonymous, module_path.split(File::PATH_SEPARATOR), manifest) end end # Provide any common methods that loaders should have. It requires that any # classes that include this module implement get # @api private module EnvironmentLoader # @!macro loader_get_or_fail def get!(name) environment = get(name) environment || raise(EnvironmentNotFound, name) end def clear_all root = Puppet.lookup(:root_environment) { nil } unless root.nil? root.instance_variable_set(:@static_catalogs, nil) root.instance_variable_set(:@rich_data, nil) end end # The base implementation is a noop, because `get` returns a new environment # each time. # # @see Puppet::Environments::Cached#guard def guard(name); end def unguard(name); end end # @!macro [new] loader_search_paths # A list of indicators of where the loader is getting its environments from. # @return [Array<String>] The URIs of the load locations # # @!macro [new] loader_list # @return [Array<Puppet::Node::Environment>] All of the environments known # to the loader # # @!macro [new] loader_get # Find a named environment # # @param name [String,Symbol] The name of environment to find # @return [Puppet::Node::Environment, nil] the requested environment or nil # if it wasn't found # # @!macro [new] loader_get_conf # Attempt to obtain the initial configuration for the environment. Not all # loaders can provide this. # # @param name [String,Symbol] The name of the environment whose configuration # we are looking up # @return [Puppet::Setting::EnvironmentConf, nil] the configuration for the # requested environment, or nil if not found or no configuration is available # # @!macro [new] loader_get_or_fail # Find a named environment or raise # Puppet::Environments::EnvironmentNotFound when the named environment is # does not exist. # # @param name [String,Symbol] The name of environment to find # @return [Puppet::Node::Environment] the requested environment # A source of pre-defined environments. # # @api private class Static include EnvironmentCreator include EnvironmentLoader def initialize(*environments) @environments = environments end # @!macro loader_search_paths def search_paths ["data:text/plain,internal"] end # @!macro loader_list def list @environments end # @!macro loader_get def get(name) @environments.find do |env| env.name == name.intern end end # Returns a basic environment configuration object tied to the environment's # implementation values. Will not interpolate. # # @!macro loader_get_conf def get_conf(name) env = get(name) if env Puppet::Settings::EnvironmentConf.static_for(env, Puppet[:environment_timeout], Puppet[:static_catalogs], Puppet[:rich_data]) else nil end end end # A source of unlisted pre-defined environments. # # Used only for internal bootstrapping environments which are not relevant # to an end user (such as the fall back 'configured' environment). # # @api private class StaticPrivate < Static # Unlisted # # @!macro loader_list def list [] end end class StaticDirectory < Static # Accepts a single environment in the given directory having the given name (not required to be reflected as the name # of the directory) def initialize(env_name, env_dir, environment) super(environment) @env_dir = env_dir @env_name = env_name.intern end # @!macro loader_get_conf def get_conf(name) return nil unless name.intern == @env_name Puppet::Settings::EnvironmentConf.load_from(@env_dir, []) end end # Reads environments from a directory on disk. Each environment is # represented as a sub-directory. The environment's manifest setting is the # `manifest` directory of the environment directory. The environment's # modulepath setting is the global modulepath (from the `[server]` section # for the server) prepended with the `modules` directory of the environment # directory. # # @api private class Directories include EnvironmentLoader def initialize(environment_dir, global_module_path) @environment_dir = Puppet::FileSystem.expand_path(environment_dir) @global_module_path = global_module_path ? global_module_path.map { |p| Puppet::FileSystem.expand_path(p) } : nil end # Generate an array of directory loaders from a path string. # @param path [String] path to environment directories # @param global_module_path [Array<String>] the global modulepath setting # @return [Array<Puppet::Environments::Directories>] An array # of configured directory loaders. def self.from_path(path, global_module_path) environments = path.split(File::PATH_SEPARATOR) environments.map do |dir| Puppet::Environments::Directories.new(dir, global_module_path) end end def self.real_path(dir) if Puppet::FileSystem.symlink?(dir) && Puppet[:versioned_environment_dirs] dir = Pathname.new Puppet::FileSystem.expand_path(Puppet::FileSystem.readlink(dir)) end dir end # @!macro loader_search_paths def search_paths ["file://#{@environment_dir}"] end # @!macro loader_list def list valid_environment_names.collect do |name| create_environment(name) end end # @!macro loader_get def get(name) if validated_directory(File.join(@environment_dir, name.to_s)) create_environment(name) end end # @!macro loader_get_conf def get_conf(name) envdir = validated_directory(File.join(@environment_dir, name.to_s)) if envdir Puppet::Settings::EnvironmentConf.load_from(envdir, @global_module_path) else nil end end private def create_environment(name) # interpolated modulepaths may be cached from prior environment instances Puppet.settings.clear_environment_settings(name) env_symbol = name.intern setting_values = Puppet.settings.values(env_symbol, Puppet.settings.preferred_run_mode) env = Puppet::Node::Environment.create( env_symbol, Puppet::Node::Environment.split_path(setting_values.interpolate(:modulepath)), setting_values.interpolate(:manifest), setting_values.interpolate(:config_version) ) configured_path = File.join(@environment_dir, name.to_s) env.configured_path = configured_path if Puppet.settings[:report_configured_environmentpath] env.resolved_path = validated_directory(configured_path) else env.resolved_path = configured_path end env end def validated_directory(envdir) env_name = Puppet::FileSystem.basename_string(envdir) envdir = Puppet::Environments::Directories.real_path(envdir).to_s if Puppet::FileSystem.directory?(envdir) && Puppet::Node::Environment.valid_name?(env_name) envdir else nil end end def valid_environment_names return [] unless Puppet::FileSystem.directory?(@environment_dir) Puppet::FileSystem.children(@environment_dir).filter_map do |child| Puppet::FileSystem.basename_string(child).intern if validated_directory(child) end end end # Combine together multiple loaders to act as one. # @api private class Combined include EnvironmentLoader def initialize(*loaders) @loaders = loaders end # @!macro loader_search_paths def search_paths @loaders.collect(&:search_paths).flatten end # @!macro loader_list def list @loaders.collect(&:list).flatten end # @!macro loader_get def get(name) @loaders.each do |loader| env = loader.get(name) if env return env end end nil end # @!macro loader_get_conf def get_conf(name) @loaders.each do |loader| conf = loader.get_conf(name) if conf return conf end end nil end def clear_all @loaders.each(&:clear_all) end end class Cached include EnvironmentLoader include Puppet::Concurrent::Synchronized class DefaultCacheExpirationService # Called when the environment is created. # # @param [Puppet::Node::Environment] env def created(env) end # Is the environment with this name expired? # # @param [Symbol] env_name The symbolic environment name # @return [Boolean] def expired?(env_name) false end # The environment with this name was evicted. # # @param [Symbol] env_name The symbolic environment name def evicted(env_name) end end def self.cache_expiration_service=(service) @cache_expiration_service_singleton = service end def self.cache_expiration_service @cache_expiration_service_singleton || DefaultCacheExpirationService.new end def initialize(loader) @loader = loader @cache_expiration_service = Puppet::Environments::Cached.cache_expiration_service @cache = {} end # @!macro loader_list def list # Evict all that have expired, in the same way as `get` clear_all_expired # Evict all that was removed from disk cached_envs = @cache.keys.map!(&:to_sym) loader_envs = @loader.list.map!(&:name) removed_envs = cached_envs - loader_envs removed_envs.each do |env_name| Puppet.debug { "Environment no longer exists '#{env_name}'" } clear(env_name) end @loader.list.map do |env| name = env.name old_entry = @cache[name] if old_entry old_entry.value else add_entry(name, entry(env)) env end end end # @!macro loader_search_paths def search_paths @loader.search_paths end # @!macro loader_get def get(name) entry = get_entry(name) entry ? entry.value : nil end # Get a cache entry for an envionment. It returns nil if the # environment doesn't exist. def get_entry(name, check_expired = true) # Aggressively evict all that has expired # This strategy favors smaller memory footprint over environment # retrieval time. clear_all_expired if check_expired name = name.to_sym entry = @cache[name] if entry Puppet.debug { "Found in cache #{name.inspect} #{entry.label}" } # found in cache entry.touch elsif (env = @loader.get(name)) # environment loaded, cache it entry = entry(env) add_entry(name, entry) end entry end private :get_entry # Adds a cache entry to the cache def add_entry(name, cache_entry) Puppet.debug { "Caching environment #{name.inspect} #{cache_entry.label}" } @cache[name] = cache_entry @cache_expiration_service.created(cache_entry.value) end private :add_entry def clear_entry(name, entry) @cache.delete(name) Puppet.debug { "Evicting cache entry for environment #{name.inspect}" } @cache_expiration_service.evicted(name.to_sym) Puppet::GettextConfig.delete_text_domain(name) Puppet.settings.clear_environment_settings(name) end private :clear_entry # Clears the cache of the environment with the given name. # (The intention is that this could be used from a MANUAL cache eviction command (TBD) def clear(name) name = name.to_sym entry = @cache[name] clear_entry(name, entry) if entry end # Clears all cached environments. # (The intention is that this could be used from a MANUAL cache eviction command (TBD) def clear_all super @cache.each_pair do |name, entry| clear_entry(name, entry) end @cache = {} Puppet::GettextConfig.delete_environment_text_domains end # Clears all environments that have expired, either by exceeding their time to live, or # through an explicit eviction determined by the cache expiration service. # def clear_all_expired t = Time.now @cache.each_pair do |name, entry| clear_if_expired(name, entry, t) end end private :clear_all_expired # Clear an environment if it is expired, either by exceeding its time to live, or # through an explicit eviction determined by the cache expiration service. # def clear_if_expired(name, entry, t = Time.now) return unless entry return if entry.guarded? if entry.expired?(t) || @cache_expiration_service.expired?(name.to_sym) clear_entry(name, entry) end end private :clear_if_expired # This implementation evicts the cache, and always gets the current # configuration of the environment # # TODO: While this is wasteful since it # needs to go on a search for the conf, it is too disruptive to optimize # this. # # @!macro loader_get_conf def get_conf(name) name = name.to_sym clear_if_expired(name, @cache[name]) @loader.get_conf(name) end # Guard an environment so it can't be evicted while it's in use. The method # may be called multiple times, provided it is unguarded the same number of # times. If you call this method, you must call `unguard` in an ensure block. def guard(name) entry = get_entry(name, false) entry.guard if entry end # Unguard an environment. def unguard(name) entry = get_entry(name, false) entry.unguard if entry end # Creates a suitable cache entry given the time to live for one environment # def entry(env) ttl = if (conf = get_conf(env.name)) conf.environment_timeout else Puppet[:environment_timeout] end case ttl when 0 NotCachedEntry.new(env) # Entry that is always expired (avoids syscall to get time) when Float::INFINITY Entry.new(env) # Entry that never expires (avoids syscall to get time) else MRUEntry.new(env, ttl) # Entry that expires in ttl from when it was last touched end end # Never evicting entry class Entry attr_reader :value def initialize(value) @value = value @guards = 0 end def touch end def expired?(now) false end def label "" end # These are not protected with a lock, because all of the Cached # methods are protected. def guarded? @guards > 0 end def guard @guards += 1 end def unguard @guards -= 1 end end # Always evicting entry class NotCachedEntry < Entry def expired?(now) true end def label "(ttl = 0 sec)" end end # Policy that expires if it hasn't been touched within ttl_seconds class MRUEntry < Entry def initialize(value, ttl_seconds) super(value) @ttl = Time.now + ttl_seconds @ttl_seconds = ttl_seconds touch end def touch @ttl = Time.now + @ttl_seconds end def expired?(now) now > @ttl end def label "(ttl = #{@ttl_seconds} sec)" end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/compilable_resource_type.rb
lib/puppet/compilable_resource_type.rb
# frozen_string_literal: true require_relative '../puppet' # The CompilableResourceType module should be either included in a class or used as a class extension # to mark that the instance used as the 'resource type' of a resource instance # is an object that is compatible with Puppet::Type's API wrt. compiling. # Puppet Resource Types written in Ruby use a meta programmed Ruby Class as the type. Those classes # are subtypes of Puppet::Type. Meta data (Pcore/puppet language) based resource types uses instances of # a class instead. # module Puppet::CompilableResourceType # All 3.x resource types implemented in Ruby using Puppet::Type respond true. # Other kinds of implementations should reimplement and return false. def is_3x_ruby_plugin? true end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/module.rb
lib/puppet/module.rb
# frozen_string_literal: true require_relative '../puppet/util/logging' require_relative 'module/task' require_relative 'module/plan' require_relative '../puppet/util/json' require 'semantic_puppet/gem_version' # Support for modules class Puppet::Module class Error < Puppet::Error; end class MissingModule < Error; end class IncompatibleModule < Error; end class UnsupportedPlatform < Error; end class IncompatiblePlatform < Error; end class MissingMetadata < Error; end class FaultyMetadata < Error; end class InvalidName < Error; end class InvalidFilePattern < Error; end include Puppet::Util::Logging FILETYPES = { "manifests" => "manifests", "files" => "files", "templates" => "templates", "plugins" => "lib", "pluginfacts" => "facts.d", "locales" => "locales", "scripts" => "scripts", } # Find and return the +module+ that +path+ belongs to. If +path+ is # absolute, or if there is no module whose name is the first component # of +path+, return +nil+ def self.find(modname, environment = nil) return nil unless modname # Unless a specific environment is given, use the current environment env = environment ? Puppet.lookup(:environments).get!(environment) : Puppet.lookup(:current_environment) env.module(modname) end def self.is_module_directory?(name, path) # it must be a directory fullpath = File.join(path, name) return false unless Puppet::FileSystem.directory?(fullpath) is_module_directory_name?(name) end def self.is_module_directory_name?(name) # it must match an installed module name according to forge validator return true if name =~ /^[a-z][a-z0-9_]*$/ false end def self.is_module_namespaced_name?(name) # it must match the full module name according to forge validator return true if name =~ /^[a-zA-Z0-9]+-[a-z][a-z0-9_]*$/ false end # @api private def self.parse_range(range) SemanticPuppet::VersionRange.parse(range) end attr_reader :name, :environment, :path, :metadata attr_writer :environment attr_accessor :dependencies, :forge_name attr_accessor :source, :author, :version, :license, :summary, :description, :project_page def initialize(name, path, environment) @name = name @path = path @environment = environment assert_validity load_metadata @absolute_path_to_manifests = Puppet::FileSystem::PathPattern.absolute(manifests) end # @deprecated The puppetversion module metadata field is no longer used. def puppetversion nil end # @deprecated The puppetversion module metadata field is no longer used. def puppetversion=(something) end # @deprecated The puppetversion module metadata field is no longer used. def validate_puppet_version nil end def has_metadata? load_metadata @metadata.is_a?(Hash) && !@metadata.empty? rescue Puppet::Module::MissingMetadata false end FILETYPES.each do |type, location| # A boolean method to let external callers determine if # we have files of a given type. define_method(type + '?') do type_subpath = subpath(location) unless Puppet::FileSystem.exist?(type_subpath) Puppet.debug { "No #{type} found in subpath '#{type_subpath}' (file / directory does not exist)" } return false end true end # A method for returning a given file of a given type. # e.g., file = mod.manifest("my/manifest.pp") # # If the file name is nil, then the base directory for the # file type is passed; this is used for fileserving. define_method(type.sub(/s$/, '')) do |file| # If 'file' is nil then they're asking for the base path. # This is used for things like fileserving. if file full_path = File.join(subpath(location), file) else full_path = subpath(location) end return nil unless Puppet::FileSystem.exist?(full_path) full_path end # Return the base directory for the given type define_method(type) do subpath(location) end end def tasks_directory subpath("tasks") end def tasks return @tasks if instance_variable_defined?(:@tasks) if Puppet::FileSystem.exist?(tasks_directory) @tasks = Puppet::Module::Task.tasks_in_module(self) else @tasks = [] end end # This is a re-implementation of the Filetypes singular type method (e.g. # `manifest('my/manifest.pp')`. We don't implement the full filetype "API" for # tasks since tasks don't map 1:1 onto files. def task_file(name) # If 'file' is nil then they're asking for the base path. # This is used for things like fileserving. if name full_path = File.join(tasks_directory, name) else full_path = tasks_directory end if Puppet::FileSystem.exist?(full_path) full_path else nil end end def plans_directory subpath("plans") end def plans return @plans if instance_variable_defined?(:@plans) if Puppet::FileSystem.exist?(plans_directory) @plans = Puppet::Module::Plan.plans_in_module(self) else @plans = [] end end # This is a re-implementation of the Filetypes singular type method (e.g. # `manifest('my/manifest.pp')`. We don't implement the full filetype "API" for # plans. def plan_file(name) # If 'file' is nil then they're asking for the base path. # This is used for things like fileserving. if name full_path = File.join(plans_directory, name) else full_path = plans_directory end if Puppet::FileSystem.exist?(full_path) full_path else nil end end def license_file return @license_file if defined?(@license_file) return @license_file = nil unless path @license_file = File.join(path, "License") end def read_metadata md_file = metadata_file return {} if md_file.nil? content = File.read(md_file, :encoding => 'utf-8') content.empty? ? {} : Puppet::Util::Json.load(content) rescue Errno::ENOENT {} rescue Puppet::Util::Json::ParseError => e # TRANSLATORS 'metadata.json' is a specific file name and should not be translated. msg = _("%{name} has an invalid and unparsable metadata.json file. The parse error: %{error}") % { name: name, error: e.message } case Puppet[:strict] when :off Puppet.debug(msg) when :warning Puppet.warning(msg) when :error raise FaultyMetadata, msg end {} end def load_metadata return if instance_variable_defined?(:@metadata) @metadata = data = read_metadata return if data.empty? @forge_name = data['name'].tr('-', '/') if data['name'] [:source, :author, :version, :license, :dependencies].each do |attr| value = data[attr.to_s] raise MissingMetadata, "No #{attr} module metadata provided for #{name}" if value.nil? if attr == :dependencies unless value.is_a?(Array) raise MissingMetadata, "The value for the key dependencies in the file metadata.json of the module #{name} must be an array, not: '#{value}'" end value.each do |dep| name = dep['name'] dep['name'] = name.tr('-', '/') unless name.nil? dep['version_requirement'] ||= '>= 0.0.0' end end send(attr.to_s + "=", value) end end # Return the list of manifests matching the given glob pattern, # defaulting to 'init.pp' for empty modules. def match_manifests(rest) if rest wanted_manifests = wanted_manifests_from(rest) searched_manifests = wanted_manifests.glob.reject { |f| FileTest.directory?(f) } else searched_manifests = [] end # (#4220) Always ensure init.pp in case class is defined there. init_manifest = manifest("init.pp") if !init_manifest.nil? && !searched_manifests.include?(init_manifest) searched_manifests.unshift(init_manifest) end searched_manifests end def all_manifests return [] unless Puppet::FileSystem.exist?(manifests) Dir.glob(File.join(manifests, '**', '*.pp')) end def metadata_file return @metadata_file if defined?(@metadata_file) return @metadata_file = nil unless path @metadata_file = File.join(path, "metadata.json") end def hiera_conf_file unless defined?(@hiera_conf_file) @hiera_conf_file = path.nil? ? nil : File.join(path, Puppet::Pops::Lookup::HieraConfig::CONFIG_FILE_NAME) end @hiera_conf_file end def has_hiera_conf? hiera_conf_file.nil? ? false : Puppet::FileSystem.exist?(hiera_conf_file) end def modulepath File.dirname(path) if path end # Find all plugin directories. This is used by the Plugins fileserving mount. def plugin_directory subpath("lib") end def plugin_fact_directory subpath("facts.d") end # @return [String] def locale_directory subpath("locales") end # Returns true if the module has translation files for the # given locale. # @param [String] locale the two-letter language code to check # for translations # @return true if the module has a directory for the locale, false # false otherwise def has_translations?(locale) Puppet::FileSystem.exist?(File.join(locale_directory, locale)) end def has_external_facts? File.directory?(plugin_fact_directory) end def supports(name, version = nil) @supports ||= [] @supports << [name, version] end def to_s result = "Module #{name}" result += "(#{path})" if path result end def dependencies_as_modules dependent_modules = [] dependencies and dependencies.each do |dep| _, dep_name = dep["name"].split('/') found_module = environment.module(dep_name) dependent_modules << found_module if found_module end dependent_modules end def required_by environment.module_requirements[forge_name] || {} end # Identify and mark unmet dependencies. A dependency will be marked unmet # for the following reasons: # # * not installed and is thus considered missing # * installed and does not meet the version requirements for this module # * installed and doesn't use semantic versioning # # Returns a list of hashes representing the details of an unmet dependency. # # Example: # # [ # { # :reason => :missing, # :name => 'puppetlabs-mysql', # :version_constraint => 'v0.0.1', # :mod_details => { # :installed_version => '0.0.1' # } # :parent => { # :name => 'puppetlabs-bacula', # :version => 'v1.0.0' # } # } # ] # def unmet_dependencies unmet_dependencies = [] return unmet_dependencies unless dependencies dependencies.each do |dependency| name = dependency['name'] version_string = dependency['version_requirement'] || '>= 0.0.0' dep_mod = begin environment.module_by_forge_name(name) rescue nil end error_details = { :name => name, :version_constraint => version_string.gsub(/^(?=\d)/, "v"), :parent => { :name => forge_name, :version => version.gsub(/^(?=\d)/, "v") }, :mod_details => { :installed_version => dep_mod.nil? ? nil : dep_mod.version } } unless dep_mod error_details[:reason] = :missing unmet_dependencies << error_details next end next unless version_string begin required_version_semver_range = self.class.parse_range(version_string) actual_version_semver = SemanticPuppet::Version.parse(dep_mod.version) rescue ArgumentError error_details[:reason] = :non_semantic_version unmet_dependencies << error_details next end next if required_version_semver_range.include? actual_version_semver error_details[:reason] = :version_mismatch unmet_dependencies << error_details next end unmet_dependencies end def ==(other) name == other.name && version == other.version && path == other.path && environment == other.environment end private def wanted_manifests_from(pattern) begin extended = File.extname(pattern).empty? ? "#{pattern}.pp" : pattern relative_pattern = Puppet::FileSystem::PathPattern.relative(extended) rescue Puppet::FileSystem::PathPattern::InvalidPattern => error raise Puppet::Module::InvalidFilePattern.new( "The pattern \"#{pattern}\" to find manifests in the module \"#{name}\" " \ "is invalid and potentially unsafe.", error ) end relative_pattern.prefix_with(@absolute_path_to_manifests) end def subpath(type) File.join(path, type) end def assert_validity if !Puppet::Module.is_module_directory_name?(@name) && !Puppet::Module.is_module_namespaced_name?(@name) raise InvalidName, _(<<-ERROR_STRING).chomp % { name: @name } Invalid module name '%{name}'; module names must match either: An installed module name (ex. modulename) matching the expression /^[a-z][a-z0-9_]*$/ -or- A namespaced module name (ex. author-modulename) matching the expression /^[a-zA-Z0-9]+[-][a-z][a-z0-9_]*$/ ERROR_STRING end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/context.rb
lib/puppet/context.rb
# frozen_string_literal: true require_relative '../puppet/thread_local' # Puppet::Context is a system for tracking services and contextual information # that puppet needs to be able to run. Values are "bound" in a context when it is created # and cannot be changed; however a child context can be created, using # {#override}, that provides a different value. # # When binding a {Proc}, the proc is called when the value is looked up, and the result # is memoized for subsequent lookups. This provides a lazy mechanism that can be used to # delay expensive production of values until they are needed. # # @api private class Puppet::Context require_relative 'context/trusted_information' class UndefinedBindingError < Puppet::Error; end class StackUnderflow < Puppet::Error; end class UnknownRollbackMarkError < Puppet::Error; end class DuplicateRollbackMarkError < Puppet::Error; end # @api private def initialize(initial_bindings) @stack = Puppet::ThreadLocal.new(EmptyStack.new.push(initial_bindings)) # By initializing @rollbacks to nil and creating a hash lazily when #mark or # #rollback are called we ensure that the hashes are never shared between # threads and it's safe to mutate them @rollbacks = Puppet::ThreadLocal.new(nil) end # @api private def push(overrides, description = '') @stack.value = @stack.value.push(overrides, description) end # Push a context and make this global across threads # Do not use in a context where multiple threads may already exist # # @api private def unsafe_push_global(overrides, description = '') @stack = Puppet::ThreadLocal.new( @stack.value.push(overrides, description) ) end # @api private def pop @stack.value = @stack.value.pop end # @api private def lookup(name, &block) @stack.value.lookup(name, &block) end # @api private def override(bindings, description = '', &block) saved_point = @stack.value push(bindings, description) yield ensure @stack.value = saved_point end # Mark a place on the context stack to later return to with {rollback}. # # @param name [Object] The identifier for the mark # # @api private def mark(name) @rollbacks.value ||= {} if @rollbacks.value[name].nil? @rollbacks.value[name] = @stack.value else raise DuplicateRollbackMarkError, _("Mark for '%{name}' already exists") % { name: name } end end # Roll back to a mark set by {mark}. # # Rollbacks can only reach a mark accessible via {pop}. If the mark is not on # the current context stack the behavior of rollback is undefined. # # @param name [Object] The identifier for the mark # # @api private def rollback(name) @rollbacks.value ||= {} if @rollbacks.value[name].nil? raise UnknownRollbackMarkError, _("Unknown mark '%{name}'") % { name: name } end @stack.value = @rollbacks.value.delete(name) end # Base case for Puppet::Context::Stack. # # @api private class EmptyStack # Lookup a binding. Since there are none in EmptyStack, this always raises # an exception unless a block is passed, in which case the block is called # and its return value is used. # # @api private def lookup(name, &block) if block block.call else raise UndefinedBindingError, _("Unable to lookup '%{name}'") % { name: name } end end # Base case of #pop always raises an error since this is the bottom # # @api private def pop raise(StackUnderflow, _('Attempted to pop, but already at root of the context stack.')) end # Push bindings onto the stack by creating a new Stack object with `self` as # the parent # # @api private def push(overrides, description = '') Puppet::Context::Stack.new(self, overrides, description) end # Return the bindings table, which is always empty here # # @api private def bindings {} end end # Internal implementation of the bindings stack used by Puppet::Context. An # instance of Puppet::Context::Stack represents one level of bindings. It # caches a merged copy of all the bindings in the stack up to this point. # Each element of the stack is immutable, allowing the base to be shared # between threads. # # @api private class Stack attr_reader :bindings def initialize(parent, bindings, description = '') @parent = parent @bindings = parent.bindings.merge(bindings || {}) @description = description end # Lookup a binding in the current stack. Return the value if it is present. # If the value is a stored Proc, evaluate, cache, and return the result. If # no binding is found and a block is passed evaluate it and return the # result. Otherwise an exception is raised. # # @api private def lookup(name, &block) if @bindings.include?(name) value = @bindings[name] value.is_a?(Proc) ? (@bindings[name] = value.call) : value elsif block block.call else raise UndefinedBindingError, _("Unable to lookup '%{name}'") % { name: name } end end # Pop one level off the stack by returning the parent object. # # @api private def pop @parent end # Push bindings onto the stack by creating a new Stack object with `self` as # the parent # # @api private def push(overrides, description = '') Puppet::Context::Stack.new(self, overrides, description) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/defaults.rb
lib/puppet/defaults.rb
# frozen_string_literal: true require_relative '../puppet/util/platform' module Puppet def self.default_diffargs '-u' end # If you modify this, update puppet/type/file/checksum.rb too def self.default_digest_algorithm 'sha256' end def self.valid_digest_algorithms Puppet::Util::Platform.fips_enabled? ? %w[sha256 sha384 sha512 sha224] : %w[sha256 sha384 sha512 sha224 md5] end def self.default_file_checksum_types Puppet::Util::Platform.fips_enabled? ? %w[sha256 sha384 sha512 sha224] : %w[sha256 sha384 sha512 sha224 md5] end def self.valid_file_checksum_types Puppet::Util::Platform.fips_enabled? ? %w[sha256 sha256lite sha384 sha512 sha224 sha1 sha1lite mtime ctime] : %w[sha256 sha256lite sha384 sha512 sha224 sha1 sha1lite md5 md5lite mtime ctime] end def self.default_cadir return "" if Puppet::Util::Platform.windows? old_ca_dir = "#{Puppet[:ssldir]}/ca" new_ca_dir = "/etc/puppetlabs/puppetserver/ca" if File.exist?(old_ca_dir) if File.symlink?(old_ca_dir) File.readlink(old_ca_dir) else old_ca_dir end else new_ca_dir end end def self.default_basemodulepath path = ['$codedir/modules'] if (run_mode_dir = Puppet.run_mode.common_module_dir) path << run_mode_dir end path.join(File::PATH_SEPARATOR) end def self.default_vendormoduledir Puppet.run_mode.vendor_module_dir end ############################################################################################ # NOTE: For information about the available values for the ":type" property of settings, # see the docs for Settings.define_settings ############################################################################################ AS_DURATION = 'This setting can be a time interval in seconds (30 or 30s), minutes (30m), hours (6h), days (2d), or years (5y).' # @api public # @param args [Puppet::Settings] the settings object to define default settings for # @return void def self.initialize_default_settings!(settings) settings.define_settings(:main, :confdir => { :default => nil, :type => :directory, :desc => "The main Puppet configuration directory. The default for this setting is calculated based on the user. If the process is running as root or the user that Puppet is supposed to run as, it defaults to a system directory, but if it's running as any other user, it defaults to being in the user's home directory.", }, :codedir => { :default => nil, :type => :directory, :desc => "The main Puppet code directory. The default for this setting is calculated based on the user. If the process is running as root or the user that Puppet is supposed to run as, it defaults to a system directory, but if it's running as any other user, it defaults to being in the user's home directory.", }, :vardir => { :default => nil, :type => :directory, :owner => "service", :group => "service", :desc => "Where Puppet stores dynamic and growing data. The default for this setting is calculated specially, like `confdir`_.", }, ### NOTE: this setting is usually being set to a symbol value. We don't officially have a ### setting type for that yet, but we might want to consider creating one. :name => { :default => nil, :desc => "The name of the application, if we are running as one. The default is essentially $0 without the path or `.rb`.", } ) settings.define_settings(:main, :logdir => { :default => nil, :type => :directory, :mode => "0750", :owner => "service", :group => "service", :desc => "The directory in which to store log files", }, :log_level => { :default => 'notice', :type => :enum, :values => %w[debug info notice warning err alert emerg crit], :desc => "Default logging level for messages from Puppet. Allowed values are: * debug * info * notice * warning * err * alert * emerg * crit ", :hook => proc {|value| Puppet::Util::Log.level = value }, :call_hook => :on_initialize_and_write, }, :disable_warnings => { :default => [], :type => :array, :desc => "A comma-separated list of warning types to suppress. If large numbers of warnings are making Puppet's logs too large or difficult to use, you can temporarily silence them with this setting. If you are preparing to upgrade Puppet to a new major version, you should re-enable all warnings for a while. Valid values for this setting are: * `deprecations` --- disables deprecation warnings. * `undefined_variables` --- disables warnings about non existing variables. * `undefined_resources` --- disables warnings about non existing resources.", :hook => proc do |value| values = munge(value) valid = %w[deprecations undefined_variables undefined_resources] invalid = values - (values & valid) unless invalid.empty? raise ArgumentError, _("Cannot disable unrecognized warning types '%{invalid}'.") % { invalid: invalid.join(',') } + ' ' + _("Valid values are '%{values}'.") % { values: valid.join(', ') } end end }, :skip_logging_catalog_request_destination => { :default => false, :type => :boolean, :desc => "Specifies whether to suppress the notice of which compiler supplied the catalog. A value of `true` suppresses the notice.", }, :merge_dependency_warnings => { :default => false, :type => :boolean, :desc => "Whether to merge class-level dependency failure warnings. When a class has a failed dependency, every resource in the class generates a notice level message about the dependency failure, and a warning level message about skipping the resource. If true, all messages caused by a class dependency failure are merged into one message associated with the class. ", }, :strict => { :default => :error, :type => :symbolic_enum, :values => [:off, :warning, :error], :desc => "The strictness level of puppet. Allowed values are: * off - do not perform extra validation, do not report * warning - perform extra validation, report as warning * error - perform extra validation, fail with error (default) The strictness level is for both language semantics and runtime evaluation validation. In addition to controlling the behavior with this primary server switch some individual warnings may also be controlled by the disable_warnings setting. No new validations will be added to a micro (x.y.z) release, but may be added in minor releases (x.y.0). In major releases it expected that most (if not all) strictness validation become standard behavior.", :hook => proc do |value| munge(value) value.to_sym end }, :disable_i18n => { :default => true, :type => :boolean, :desc => "If true, turns off all translations of Puppet and module log messages, which affects error, warning, and info log messages, as well as any translations in the report and CLI.", :hook => proc do |value| if value require_relative '../puppet/gettext/stubs' Puppet::GettextConfig.disable_gettext end end } ) settings.define_settings(:main, :priority => { :default => nil, :type => :priority, :desc => "The scheduling priority of the process. Valid values are 'high', 'normal', 'low', or 'idle', which are mapped to platform-specific values. The priority can also be specified as an integer value and will be passed as is, e.g. -5. Puppet must be running as a privileged user in order to increase scheduling priority.", }, :trace => { :default => false, :type => :boolean, :desc => "Whether to print stack traces on some errors. Will print internal Ruby stack trace interleaved with Puppet function frames.", :hook => proc do |value| # Enable or disable Facter's trace option too Puppet.runtime[:facter].trace(value) end }, :puppet_trace => { :default => false, :type => :boolean, :desc => "Whether to print the Puppet stack trace on some errors. This is a noop if `trace` is also set.", }, :profile => { :default => false, :type => :boolean, :desc => "Whether to enable experimental performance profiling", }, :versioned_environment_dirs => { :default => false, :type => :boolean, :desc => "Whether or not to look for versioned environment directories, symlinked from `$environmentpath/<environment>`. This is an experimental feature and should be used with caution." }, :static_catalogs => { :default => true, :type => :boolean, :desc => "Whether to compile a [static catalog](https://puppet.com/docs/puppet/latest/static_catalogs.html#enabling-or-disabling-static-catalogs), which occurs only on Puppet Server when the `code-id-command` and `code-content-command` settings are configured in its `puppetserver.conf` file.", }, :settings_catalog => { :default => true, :type => :boolean, :desc => "Whether to compile and apply the settings catalog", }, :strict_environment_mode => { :default => false, :type => :boolean, :desc => "Whether the agent specified environment should be considered authoritative, causing the run to fail if the retrieved catalog does not match it.", }, :autoflush => { :default => true, :type => :boolean, :desc => "Whether log files should always flush to disk.", :hook => proc { |value| Log.autoflush = value } }, :syslogfacility => { :default => "daemon", :desc => "What syslog facility to use when logging to syslog. Syslog has a fixed list of valid facilities, and you must choose one of those; you cannot just make one up." }, :statedir => { :default => "$vardir/state", :type => :directory, :mode => "01755", :desc => "The directory where Puppet state is stored. Generally, this directory can be removed without causing harm (although it might result in spurious service restarts)." }, :rundir => { :default => nil, :type => :directory, :mode => "0755", :owner => "service", :group => "service", :desc => "Where Puppet PID files are kept." }, :genconfig => { :default => false, :type => :boolean, :desc => "When true, causes Puppet applications to print an example config file to stdout and exit. The example will include descriptions of each setting, and the current (or default) value of each setting, incorporating any settings overridden on the CLI (with the exception of `genconfig` itself). This setting only makes sense when specified on the command line as `--genconfig`.", }, :genmanifest => { :default => false, :type => :boolean, :desc => "Whether to just print a manifest to stdout and exit. Only makes sense when specified on the command line as `--genmanifest`. Takes into account arguments specified on the CLI.", }, :configprint => { :default => "", :deprecated => :completely, :desc => "Prints the value of a specific configuration setting. If the name of a setting is provided for this, then the value is printed and puppet exits. Comma-separate multiple values. For a list of all values, specify 'all'. This setting is deprecated, the 'puppet config' command replaces this functionality.", }, :color => { :default => "ansi", :type => :string, :desc => "Whether to use colors when logging to the console. Valid values are `ansi` (equivalent to `true`), `html`, and `false`, which produces no color." }, :mkusers => { :default => false, :type => :boolean, :desc => "Whether to create the necessary user and group that puppet agent will run as.", }, :manage_internal_file_permissions => { :default => ! Puppet::Util::Platform.windows?, :type => :boolean, :desc => "Whether Puppet should manage the owner, group, and mode of files it uses internally. **Note**: For Windows agents, the default is `false` for versions 4.10.13 and greater, versions 5.5.6 and greater, and versions 6.0 and greater.", }, :onetime => { :default => false, :type => :boolean, :desc => "Perform one configuration run and exit, rather than spawning a long-running daemon. This is useful for interactively running puppet agent, or running puppet agent from cron.", :short => 'o', }, :path => { :default => "none", :desc => "The shell search path. Defaults to whatever is inherited from the parent process. This setting can only be set in the `[main]` section of puppet.conf; it cannot be set in `[server]`, `[agent]`, or an environment config section.", :call_hook => :on_define_and_write, :hook => proc do |value| ENV['PATH'] = '' if ENV['PATH'].nil? ENV['PATH'] = value unless value == 'none' paths = ENV['PATH'].split(File::PATH_SEPARATOR) Puppet::Util::Platform.default_paths.each do |path| next if paths.include?(path) ENV['PATH'] = ENV.fetch('PATH', nil) + File::PATH_SEPARATOR + path end value end }, :libdir => { :type => :directory, :default => "$vardir/lib", :desc => "An extra search path for Puppet. This is only useful for those files that Puppet will load on demand, and is only guaranteed to work for those cases. In fact, the autoload mechanism is responsible for making sure this directory is in Ruby's search path\n" }, :environment => { :default => "production", :desc => "The environment in which Puppet is running. For clients, such as `puppet agent`, this determines the environment itself, which Puppet uses to find modules and much more. For servers, such as `puppet server`, this provides the default environment for nodes that Puppet knows nothing about. When defining an environment in the `[agent]` section, this refers to the environment that the agent requests from the primary server. The environment doesn't have to exist on the local filesystem because the agent fetches it from the primary server. This definition is used when running `puppet agent`. When defined in the `[user]` section, the environment refers to the path that Puppet uses to search for code and modules related to its execution. This requires the environment to exist locally on the filesystem where puppet is being executed. Puppet subcommands, including `puppet module` and `puppet apply`, use this definition. Given that the context and effects vary depending on the [config section](https://puppet.com/docs/puppet/latest/config_file_main.html#config-sections) in which the `environment` setting is defined, do not set it globally.", :short => "E" }, :environmentpath => { :default => "$codedir/environments", :desc => "A search path for directory environments, as a list of directories separated by the system path separator character. (The POSIX path separator is ':', and the Windows path separator is ';'.) This setting must have a value set to enable **directory environments.** The recommended value is `$codedir/environments`. For more details, see <https://puppet.com/docs/puppet/latest/environments_about.html>", :type => :path, }, :report_configured_environmentpath => { :type => :boolean, :default => true, :desc => <<-'EOT' Specifies how environment paths are reported. When the value of `versioned_environment_dirs` is `true`, Puppet applies the readlink function to the `environmentpath` setting when constructing the environment's modulepath. The full readlinked path is referred to as the "resolved path," and the configured path potentially containing symlinks is the "configured path." When reporting where resources come from, users may choose between the configured and resolved path. When set to `false`, the resolved paths are reported instead of the configured paths. EOT }, :use_last_environment => { :type => :boolean, :default => true, :desc => <<-'EOT' Puppet saves both the initial and converged environment in the last_run_summary file. If they differ, and this setting is set to true, we will use the last converged environment and skip the node request. When set to false, we will do the node request and ignore the environment data from the last_run_summary file. EOT }, :always_retry_plugins => { :type => :boolean, :default => true, :desc => <<-'EOT' Affects how we cache attempts to load Puppet resource types and features. If true, then calls to `Puppet.type.<type>?` `Puppet.feature.<feature>?` will always attempt to load the type or feature (which can be an expensive operation) unless it has already been loaded successfully. This makes it possible for a single agent run to, e.g., install a package that provides the underlying capabilities for a type or feature, and then later load that type or feature during the same run (even if the type or feature had been tested earlier and had not been available). If this setting is set to false, then types and features will only be checked once, and if they are not available, the negative result is cached and returned for all subsequent attempts to load the type or feature. This behavior is almost always appropriate for the server, and can result in a significant performance improvement for types and features that are checked frequently. EOT }, :diff_args => { :default => -> { default_diffargs }, :desc => "Which arguments to pass to the diff command when printing differences between files. The command to use can be chosen with the `diff` setting.", }, :diff => { :default => (Puppet::Util::Platform.windows? ? "" : "diff"), :desc => "Which diff command to use when printing differences between files. This setting has no default value on Windows, as standard `diff` is not available, but Puppet can use many third-party diff tools.", }, :show_diff => { :type => :boolean, :default => false, :desc => "Whether to log and report a contextual diff when files are being replaced. This causes partial file contents to pass through Puppet's normal logging and reporting system, so this setting should be used with caution if you are sending Puppet's reports to an insecure destination. This feature currently requires the `diff/lcs` Ruby library.", }, :daemonize => { :type => :boolean, :default => !Puppet::Util::Platform.windows?, :desc => "Whether to send the process into the background. This defaults to true on POSIX systems, and to false on Windows (where Puppet currently cannot daemonize).", :short => "D", :hook => proc do |value| if value and Puppet::Util::Platform.windows? raise "Cannot daemonize on Windows" end end }, :maximum_uid => { :default => 4_294_967_290, :type => :integer, :desc => "The maximum allowed UID. Some platforms use negative UIDs but then ship with tools that do not know how to handle signed ints, so the UIDs show up as huge numbers that can then not be fed back into the system. This is a hackish way to fail in a slightly more useful way when that happens.", }, :route_file => { :default => "$confdir/routes.yaml", :desc => "The YAML file containing indirector route configuration.", }, :node_terminus => { :type => :terminus, :default => "plain", :desc => <<-'EOT', Which node data plugin to use when compiling node catalogs. When Puppet compiles a catalog, it combines two primary sources of info: the main manifest, and a node data plugin (often called a "node terminus," for historical reasons). Node data plugins provide three things for a given node name: 1. A list of classes to add to that node's catalog (and, optionally, values for their parameters). 2. Which Puppet environment the node should use. 3. A list of additional top-scope variables to set. The three main node data plugins are: * `plain` --- Returns no data, so that the main manifest controls all node configuration. * `exec` --- Uses an [external node classifier (ENC)](https://puppet.com/docs/puppet/latest/nodes_external.html), configured by the `external_nodes` setting. This lets you pull a list of Puppet classes from any external system, using a small glue script to perform the request and format the result as YAML. * `classifier` (formerly `console`) --- Specific to Puppet Enterprise. Uses the PE console for node data." EOT }, :node_cache_terminus => { :type => :terminus, :default => nil, :desc => "How to store cached nodes. Valid values are (none), 'json', 'msgpack', or 'yaml'.", }, :data_binding_terminus => { :type => :terminus, :default => "hiera", :desc => "This setting has been deprecated. Use of any value other than 'hiera' should instead be configured in a version 5 hiera.yaml. Until this setting is removed, it controls which data binding terminus to use for global automatic data binding (across all environments). By default this value is 'hiera'. A value of 'none' turns off the global binding.", :call_hook => :on_initialize_and_write, :hook => proc do |value| if Puppet[:strict] != :off s_val = value.to_s # because sometimes the value is a symbol unless s_val == 'hiera' || s_val == 'none' || value == '' || value.nil? #TRANSLATORS 'data_binding_terminus' is a setting and should not be translated message = _("Setting 'data_binding_terminus' is deprecated.") #TRANSLATORS 'hiera' should not be translated message += ' ' + _("Convert custom terminus to hiera 5 API.") Puppet.deprecation_warning(message) end end end }, :hiera_config => { :default => lambda do config = nil codedir = settings[:codedir] if codedir.is_a?(String) config = File.expand_path(File.join(codedir, 'hiera.yaml')) config = nil unless Puppet::FileSystem.exist?(config) end config = File.expand_path(File.join(settings[:confdir], 'hiera.yaml')) if config.nil? config end, :desc => "The hiera configuration file. Puppet only reads this file on startup, so you must restart the puppet server every time you edit it.", :type => :file, }, :binder_config => { :default => nil, :desc => "The binder configuration file. Puppet reads this file on each request to configure the bindings system. If set to nil (the default), a $confdir/binder_config.yaml is optionally loaded. If it does not exists, a default configuration is used. If the setting :binding_config is specified, it must reference a valid and existing yaml file.", :type => :file, }, :catalog_terminus => { :type => :terminus, :default => "compiler", :desc => "Where to get node catalogs. This is useful to change if, for instance, you'd like to pre-compile catalogs and store them in memcached or some other easily-accessed store.", }, :catalog_cache_terminus => { :type => :terminus, :default => nil, :desc => "How to store cached catalogs. Valid values are 'json', 'msgpack' and 'yaml'. The agent application defaults to 'json'." }, :facts_terminus => { :default => 'facter', :desc => "The node facts terminus.", }, :trusted_external_command => { :default => nil, :type => :file_or_directory, :desc => "The external trusted facts script or directory to use. This setting's value can be set to the path to an executable command that can produce external trusted facts or to a directory containing those executable commands. The command(s) must: * Take the name of a node as a command-line argument. * Return a JSON hash with the external trusted facts for this node. * For unknown or invalid nodes, exit with a non-zero exit code. If the setting points to an executable command, then the external trusted facts will be stored in the 'external' key of the trusted facts hash. Otherwise for each executable file in the directory, the external trusted facts will be stored in the `<basename>` key of the `trusted['external']` hash. For example, if the files foo.rb and bar.sh are in the directory, then `trusted['external']` will be the hash `{ 'foo' => <foo.rb output>, 'bar' => <bar.sh output> }`.", }, :default_file_terminus => { :type => :terminus, :default => "rest", :desc => "The default source for files if no server is given in a uri, e.g. puppet:///file. The default of `rest` causes the file to be retrieved using the `server` setting. When running `apply` the default is `file_server`, causing requests to be filled locally." }, :http_proxy_host => { :default => "none", :desc => "The HTTP proxy host to use for outgoing connections. The proxy will be bypassed if the server's hostname matches the NO_PROXY environment variable or `no_proxy` setting. Note: You may need to use a FQDN for the server hostname when using a proxy. Environment variable http_proxy or HTTP_PROXY will override this value. ", }, :http_proxy_port => { :default => 3128, :type => :port, :desc => "The HTTP proxy port to use for outgoing connections", }, :http_proxy_user => { :default => "none", :desc => "The user name for an authenticated HTTP proxy. Requires the `http_proxy_host` setting.", }, :http_proxy_password =>{ :default => "none", :hook => proc do |value| if value =~ %r{[@!# /]} raise "Passwords set in the http_proxy_password setting must be valid as part of a URL, and any reserved characters must be URL-encoded. We received: #{value}" end end, :desc => "The password for the user of an authenticated HTTP proxy. Requires the `http_proxy_user` setting. Note that passwords must be valid when used as part of a URL. If a password contains any characters with special meanings in URLs (as specified by RFC 3986 section 2.2), they must be URL-encoded. (For example, `#` would become `%23`.)", }, :no_proxy => { :default => "localhost, 127.0.0.1", :desc => "List of host or domain names that should not go through `http_proxy_host`. Environment variable no_proxy or NO_PROXY will override this value. Names can be specified as an FQDN `host.example.com`, wildcard `*.example.com`, dotted domain `.example.com`, or suffix `example.com`.", }, :http_keepalive_timeout => { :default => "4s", :type => :duration, :desc => "The maximum amount of time a persistent HTTP connection can remain idle in the connection pool, before it is closed. This timeout should be shorter than the keepalive timeout used on the HTTP server, e.g. Apache KeepAliveTimeout directive. #{AS_DURATION}" }, :http_debug => { :default => false, :type => :boolean, :desc => "Whether to write HTTP request and responses to stderr. This should never be used in a production environment." }, :http_connect_timeout => { :default => "2m", :type => :duration, :desc => "The maximum amount of time to wait when establishing an HTTP connection. The default value is 2 minutes. #{AS_DURATION}", }, :http_read_timeout => { :default => "10m", :type => :duration, :desc => "The time to wait for data to be read from an HTTP connection. If nothing is read after the elapsed interval then the connection will be closed. The default value is 10 minutes. #{AS_DURATION}", }, :http_user_agent => { :default => "Puppet/#{Puppet.version} Ruby/#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL} (#{RUBY_PLATFORM})", :desc => "The HTTP User-Agent string to send when making network requests." }, :filetimeout => { :default => "15s", :type => :duration, :desc => "The minimum time to wait between checking for updates in configuration files. This timeout determines how quickly Puppet checks whether a file (such as manifests or puppet.conf) has changed on disk. The default will change in a future release to be 'unlimited', requiring a reload of the Puppet service to pick up changes to its internal configuration. Currently we do not accept a value of 'unlimited'. To reparse files within an environment in Puppet Server please use the environment_cache endpoint", :hook => proc do |val| unless [0, 15, '15s'].include?(val) Puppet.deprecation_warning(<<-WARNING) Fine grained control of filetimeouts is deprecated. In future releases this value will only determine if file content is cached. Valid values are 0 (never cache) and 15 (15 second minimum wait time). WARNING end end }, :environment_timeout => { :default => "0", :type => :ttl, :desc => "How long the Puppet server should cache data it loads from an environment. A value of `0` will disable caching. This setting can also be set to `unlimited`, which will cache environments until the server is restarted or told to refresh the cache. All other values will result in Puppet server evicting environments that haven't been used within the last `environment_timeout` seconds. You should change this setting once your Puppet deployment is doing non-trivial work. We chose the default value of `0` because it lets new users update their code without any extra steps, but it lowers the performance of your Puppet server. We recommend either: * Setting this to `unlimited` and explicitly refreshing your Puppet server
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/coercion.rb
lib/puppet/coercion.rb
# frozen_string_literal: true # Various methods used to coerce values into a canonical form. # # @api private module Puppet::Coercion # Try to coerce various input values into boolean true/false # # Only a very limited subset of values are allowed. This method does not try # to provide a generic "truthiness" system. # # @param value [Boolean, Symbol, String] # @return [Boolean] # @raise # @api private def self.boolean(value) # downcase strings if value.respond_to? :downcase value = value.downcase end case value when true, :true, 'true', :yes, 'yes' # rubocop:disable Lint/BooleanSymbol true when false, :false, 'false', :no, 'no' # rubocop:disable Lint/BooleanSymbol false else fail('expected a boolean value') end end # Return the list of acceptable boolean values. # # This is limited to lower-case, even though boolean() is case-insensitive. # # @return [Array] # @raise # @api private def self.boolean_values %w[true false yes no] end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions.rb
lib/puppet/functions.rb
# frozen_string_literal: true # Functions in the puppet language can be written in Ruby and distributed in # puppet modules. The function is written by creating a file in the module's # `lib/puppet/functions/<modulename>` directory, where `<modulename>` is # replaced with the module's name. The file should have the name of the function. # For example, to create a function named `min` in a module named `math` create # a file named `lib/puppet/functions/math/min.rb` in the module. # # A function is implemented by calling {Puppet::Functions.create_function}, and # passing it a block that defines the implementation of the function. # # Functions are namespaced inside the module that contains them. The name of # the function is prefixed with the name of the module. For example, # `math::min`. # # @example A simple function # Puppet::Functions.create_function('math::min') do # def min(a, b) # a <= b ? a : b # end # end # # Anatomy of a function # --- # # Functions are composed of four parts: the name, the implementation methods, # the signatures, and the dispatches. # # The name is the string given to the {Puppet::Functions.create_function} # method. It specifies the name to use when calling the function in the puppet # language, or from other functions. # # The implementation methods are ruby methods (there can be one or more) that # provide that actual implementation of the function's behavior. In the # simplest case the name of the function (excluding any namespace) and the name # of the method are the same. When that is done no other parts (signatures and # dispatches) need to be used. # # Signatures are a way of specifying the types of the function's parameters. # The types of any arguments will be checked against the types declared in the # signature and an error will be produced if they don't match. The types are # defined by using the same syntax for types as in the puppet language. # # Dispatches are how signatures and implementation methods are tied together. # When the function is called, puppet searches the signatures for one that # matches the supplied arguments. Each signature is part of a dispatch, which # specifies the method that should be called for that signature. When a # matching signature is found, the corresponding method is called. # # Special dispatches designed to create error messages for an argument mismatch # can be added using the keyword `argument_mismatch` instead of `dispatch`. The # method appointed by an `argument_mismatch` will be called with arguments # just like a normal `dispatch` would, but the method must produce a string. # The string is then used as the message in the `ArgumentError` that is raised # when the method returns. A block parameter can be given, but it is not # propagated in the method call. # # Documentation for the function should be placed as comments to the # implementation method(s). # # @todo Documentation for individual instances of these new functions is not # yet tied into the puppet doc system. # # @example Dispatching to different methods by type # Puppet::Functions.create_function('math::min') do # dispatch :numeric_min do # param 'Numeric', :a # param 'Numeric', :b # end # # dispatch :string_min do # param 'String', :a # param 'String', :b # end # # def numeric_min(a, b) # a <= b ? a : b # end # # def string_min(a, b) # a.downcase <= b.downcase ? a : b # end # end # # @example Using an argument mismatch handler # Puppet::Functions.create_function('math::min') do # dispatch :numeric_min do # param 'Numeric', :a # param 'Numeric', :b # end # # argument_mismatch :on_error do # param 'Any', :a # param 'Any', :b # end # # def numeric_min(a, b) # a <= b ? a : b # end # # def on_error(a, b) # 'both arguments must be of type Numeric' # end # end # # Specifying Signatures # --- # # If nothing is specified, the number of arguments given to the function must # be the same as the number of parameters, and all of the parameters are of # type 'Any'. # # The following methods can be used to define a parameter # # - _param_ - the argument must be given in the call. # - _optional_param_ - the argument may be missing in the call. May not be followed by a required parameter # - _repeated_param_ - the type specifies a repeating type that occurs 0 to "infinite" number of times. It may only appear last or just before a block parameter. # - _block_param_ - a block must be given in the call. May only appear last. # - _optional_block_param_ - a block may be given in the call. May only appear last. # # The method name _required_param_ is an alias for _param_ and _required_block_param_ is an alias for _block_param_ # # A parameter definition takes 2 arguments: # - _type_ A string that must conform to a type in the puppet language # - _name_ A symbol denoting the parameter name # # Both arguments are optional when defining a block parameter. The _type_ defaults to "Callable" # and the _name_ to :block. # # Note that the dispatch definition is used to match arguments given in a call to the function with the defined # parameters. It then dispatches the call to the implementation method simply passing the given arguments on to # that method without any further processing and it is the responsibility of that method's implementor to ensure # that it can handle those arguments. # # @example Variable number of arguments # Puppet::Functions.create_function('foo') do # dispatch :foo do # param 'Numeric', :first # repeated_param 'Numeric', :values # end # # def foo(first, *values) # # do something # end # end # # There is no requirement for direct mapping between parameter definitions and the parameters in the # receiving implementation method so the following example is also legal. Here the dispatch will ensure # that `*values` in the receiver will be an array with at least one entry of type String and that any # remaining entries are of type Numeric: # # @example Inexact mapping or parameters # Puppet::Functions.create_function('foo') do # dispatch :foo do # param 'String', :first # repeated_param 'Numeric', :values # end # # def foo(*values) # # do something # end # end # # Access to Scope # --- # In general, functions should not need access to scope; they should be # written to act on their given input only. If they absolutely must look up # variable values, they should do so via the closure scope (the scope where # they are defined) - this is done by calling `closure_scope()`. # # Calling other Functions # --- # Calling other functions by name is directly supported via # {Puppet::Pops::Functions::Function#call_function}. This allows a function to # call other functions visible from its loader. # # @api public module Puppet::Functions # @param func_name [String, Symbol] a simple or qualified function name # @param block [Proc] the block that defines the methods and dispatch of the # Function to create # @return [Class<Function>] the newly created Function class # # @api public def self.create_function(func_name, function_base = Function, &block) # Ruby < 2.1.0 does not have method on Binding, can only do eval # and it will fail unless protected with an if defined? if the local # variable does not exist in the block's binder. # loader = block.binding.eval('loader_injected_arg if defined?(loader_injected_arg)') create_loaded_function(func_name, loader, function_base, &block) rescue StandardError => e raise ArgumentError, _("Function Load Error for function '%{function_name}': %{message}") % { function_name: func_name, message: e.message } end # Creates a function in, or in a local loader under the given loader. # This method should only be used when manually creating functions # for the sake of testing. Functions that are autoloaded should # always use the `create_function` method and the autoloader will supply # the correct loader. # # @param func_name [String, Symbol] a simple or qualified function name # @param loader [Puppet::Pops::Loaders::Loader] the loader loading the function # @param block [Proc] the block that defines the methods and dispatch of the # Function to create # @return [Class<Function>] the newly created Function class # # @api public def self.create_loaded_function(func_name, loader, function_base = Function, &block) if function_base.ancestors.none? { |s| s == Puppet::Pops::Functions::Function } raise ArgumentError, _("Functions must be based on Puppet::Pops::Functions::Function. Got %{function_base}") % { function_base: function_base } end func_name = func_name.to_s # Creates an anonymous class to represent the function # The idea being that it is garbage collected when there are no more # references to it. # # (Do not give the class the block here, as instance variables should be set first) the_class = Class.new(function_base) unless loader.nil? the_class.instance_variable_set(:'@loader', loader.private_loader) end # Make the anonymous class appear to have the class-name <func_name> # Even if this class is not bound to such a symbol in a global ruby scope and # must be resolved via the loader. # This also overrides any attempt to define a name method in the given block # (Since it redefines it) # # TODO, enforce name in lower case (to further make it stand out since Ruby # class names are upper case) # the_class.instance_eval do @func_name = func_name def name @func_name end def loader @loader end end # The given block can now be evaluated and have access to name and loader # the_class.class_eval(&block) # Automatically create an object dispatcher based on introspection if the # loaded user code did not define any dispatchers. Fail if function name # does not match a given method name in user code. # if the_class.dispatcher.empty? simple_name = func_name.split(/::/)[-1] type, names = default_dispatcher(the_class, simple_name) last_captures_rest = (type.size_range[1] == Float::INFINITY) the_class.dispatcher.add(Puppet::Pops::Functions::Dispatch.new(type, simple_name, names, last_captures_rest)) end # The function class is returned as the result of the create function method the_class end # Creates a default dispatcher configured from a method with the same name as the function # # @api private def self.default_dispatcher(the_class, func_name) unless the_class.method_defined?(func_name) raise ArgumentError, _("Function Creation Error, cannot create a default dispatcher for function '%{func_name}', no method with this name found") % { func_name: func_name } end any_signature(*min_max_param(the_class.instance_method(func_name))) end # @api private def self.min_max_param(method) result = { :req => 0, :opt => 0, :rest => 0 } # count per parameter kind, and get array of names names = method.parameters.map { |p| result[p[0]] += 1; p[1].to_s } from = result[:req] to = result[:rest] > 0 ? :default : from + result[:opt] [from, to, names] end # Construct a signature consisting of Object type, with min, and max, and given names. # (there is only one type entry). # # @api private def self.any_signature(from, to, names) # Construct the type for the signature # Tuple[Object, from, to] param_types = Puppet::Pops::Types::PTupleType.new([Puppet::Pops::Types::PAnyType::DEFAULT], Puppet::Pops::Types::PIntegerType.new(from, to)) [Puppet::Pops::Types::PCallableType.new(param_types), names] end # Function # === # This class is the base class for all Puppet 4x Function API functions. A # specialized class is created for each puppet function. # # @api public class Function < Puppet::Pops::Functions::Function # @api private def self.builder DispatcherBuilder.new(dispatcher, Puppet::Pops::Types::PCallableType::DEFAULT, loader) end # Dispatch any calls that match the signature to the provided method name. # # @param meth_name [Symbol] The name of the implementation method to call # when the signature defined in the block matches the arguments to a call # to the function. # @return [Void] # # @api public def self.dispatch(meth_name, &block) builder().instance_eval do dispatch(meth_name, false, &block) end end # Like `dispatch` but used for a specific type of argument mismatch. Will not be include in the list of valid # parameter overloads for the function. # # @param meth_name [Symbol] The name of the implementation method to call # when the signature defined in the block matches the arguments to a call # to the function. # @return [Void] # # @api public def self.argument_mismatch(meth_name, &block) builder().instance_eval do dispatch(meth_name, true, &block) end end # Allows types local to the function to be defined to ease the use of complex types # in a 4.x function. Within the given block, calls to `type` can be made with a string # 'AliasType = ExistingType` can be made to define aliases. The defined aliases are # available for further aliases, and in all dispatchers. # # @since 4.5.0 # @api public # def self.local_types(&block) if loader.nil? raise ArgumentError, _("No loader present. Call create_loaded_function(:myname, loader,...), instead of 'create_function' if running tests") end aliases = LocalTypeAliasesBuilder.new(loader, name) aliases.instance_eval(&block) # Add the loaded types to the builder aliases.local_types.each do |type_alias_expr| # Bind the type alias to the local_loader using the alias t = Puppet::Pops::Loader::TypeDefinitionInstantiator.create_from_model(type_alias_expr, aliases.loader) # Also define a method for convenient access to the defined type alias. # Since initial capital letter in Ruby means a Constant these names use a prefix of # `type`. As an example, the type 'MyType' is accessed by calling `type_MyType`. define_method("type_#{t.name}") { t } end # Store the loader in the class @loader = aliases.loader end # Creates a new function instance in the given closure scope (visibility to variables), and a loader # (visibility to other definitions). The created function will either use the `given_loader` or # (if it has local type aliases) a loader that was constructed from the loader used when loading # the function's class. # # TODO: It would be of value to get rid of the second parameter here, but that would break API. # def self.new(closure_scope, given_loader) super(closure_scope, @loader || given_loader) end end # Base class for all functions implemented in the puppet language class PuppetFunction < Function def self.init_dispatch(a_closure) # A closure is compatible with a dispatcher - they are both callable signatures dispatcher.add(a_closure) end end # Public api methods of the DispatcherBuilder are available within dispatch() # blocks declared in a Puppet::Function.create_function() call. # # @api public class DispatcherBuilder attr_reader :loader # @api private def initialize(dispatcher, all_callables, loader) @all_callables = all_callables @dispatcher = dispatcher @loader = loader end # Defines a required positional parameter with _type_ and _name_. # # @param type [String] The type specification for the parameter. # @param name [Symbol] The name of the parameter. This is primarily used # for error message output and does not have to match an implementation # method parameter. # @return [Void] # # @api public def param(type, name) internal_param(type, name) raise ArgumentError, _('A required parameter cannot be added after an optional parameter') if @min != @max @min += 1 @max += 1 end alias required_param param # Defines an optional positional parameter with _type_ and _name_. # May not be followed by a required parameter. # # @param type [String] The type specification for the parameter. # @param name [Symbol] The name of the parameter. This is primarily used # for error message output and does not have to match an implementation # method parameter. # @return [Void] # # @api public def optional_param(type, name) internal_param(type, name) @max += 1 end # Defines a repeated positional parameter with _type_ and _name_ that may occur 0 to "infinite" number of times. # It may only appear last or just before a block parameter. # # @param type [String] The type specification for the parameter. # @param name [Symbol] The name of the parameter. This is primarily used # for error message output and does not have to match an implementation # method parameter. # @return [Void] # # @api public def repeated_param(type, name) internal_param(type, name, true) @max = :default end alias optional_repeated_param repeated_param # Defines a repeated positional parameter with _type_ and _name_ that may occur 1 to "infinite" number of times. # It may only appear last or just before a block parameter. # # @param type [String] The type specification for the parameter. # @param name [Symbol] The name of the parameter. This is primarily used # for error message output and does not have to match an implementation # method parameter. # @return [Void] # # @api public def required_repeated_param(type, name) internal_param(type, name, true) raise ArgumentError, _('A required repeated parameter cannot be added after an optional parameter') if @min != @max @min += 1 @max = :default end # Defines one required block parameter that may appear last. If type and name is missing the # default type is "Callable", and the name is "block". If only one # parameter is given, then that is the name and the type is "Callable". # # @api public def block_param(*type_and_name) case type_and_name.size when 0 type = @all_callables name = :block when 1 type = @all_callables name = type_and_name[0] when 2 type, name = type_and_name type = Puppet::Pops::Types::TypeParser.singleton.parse(type, loader) unless type.is_a?(Puppet::Pops::Types::PAnyType) else raise ArgumentError, _("block_param accepts max 2 arguments (type, name), got %{size}.") % { size: type_and_name.size } end unless Puppet::Pops::Types::TypeCalculator.is_kind_of_callable?(type, false) raise ArgumentError, _("Expected PCallableType or PVariantType thereof, got %{type_class}") % { type_class: type.class } end unless name.is_a?(Symbol) raise ArgumentError, _("Expected block_param name to be a Symbol, got %{name_class}") % { name_class: name.class } end if @block_type.nil? @block_type = type @block_name = name else raise ArgumentError, _('Attempt to redefine block') end end alias required_block_param block_param # Defines one optional block parameter that may appear last. If type or name is missing the # defaults are "any callable", and the name is "block". The implementor of the dispatch target # must use block = nil when it is optional (or an error is raised when the call is made). # # @api public def optional_block_param(*type_and_name) # same as required, only wrap the result in an optional type required_block_param(*type_and_name) @block_type = Puppet::Pops::Types::TypeFactory.optional(@block_type) end # Defines the return type. Defaults to 'Any' # @param [String] type a reference to a Puppet Data Type # # @api public def return_type(type) unless type.is_a?(String) || type.is_a?(Puppet::Pops::Types::PAnyType) raise ArgumentError, _("Argument to 'return_type' must be a String reference to a Puppet Data Type. Got %{type_class}") % { type_class: type.class } end @return_type = type end private # @api private def internal_param(type, name, repeat = false) raise ArgumentError, _('Parameters cannot be added after a block parameter') unless @block_type.nil? raise ArgumentError, _('Parameters cannot be added after a repeated parameter') if @max == :default if name.is_a?(String) raise ArgumentError, _("Parameter name argument must be a Symbol. Got %{name_class}") % { name_class: name.class } end if type.is_a?(String) || type.is_a?(Puppet::Pops::Types::PAnyType) @types << type @names << name # mark what should be picked for this position when dispatching if repeat @weaving << -@names.size() else @weaving << @names.size() - 1 end else raise ArgumentError, _("Parameter 'type' must be a String reference to a Puppet Data Type. Got %{type_class}") % { type_class: type.class } end end # @api private def dispatch(meth_name, argument_mismatch_handler, &block) # an array of either an index into names/types, or an array with # injection information [type, name, injection_name] used when the call # is being made to weave injections into the given arguments. # @types = [] @names = [] @weaving = [] @injections = [] @min = 0 @max = 0 @block_type = nil @block_name = nil @return_type = nil @argument_mismatch_hander = argument_mismatch_handler instance_eval(&block) callable_t = create_callable(@types, @block_type, @return_type, @min, @max) @dispatcher.add(Puppet::Pops::Functions::Dispatch.new(callable_t, meth_name, @names, @max == :default, @block_name, @injections, @weaving, @argument_mismatch_hander)) end # Handles creation of a callable type from strings specifications of puppet # types and allows the min/max occurs of the given types to be given as one # or two integer values at the end. The given block_type should be # Optional[Callable], Callable, or nil. # # @api private def create_callable(types, block_type, return_type, from, to) mapped_types = types.map do |t| t.is_a?(Puppet::Pops::Types::PAnyType) ? t : internal_type_parse(t, loader) end param_types = Puppet::Pops::Types::PTupleType.new(mapped_types, from > 0 && from == to ? nil : Puppet::Pops::Types::PIntegerType.new(from, to)) return_type = internal_type_parse(return_type, loader) unless return_type.nil? || return_type.is_a?(Puppet::Pops::Types::PAnyType) Puppet::Pops::Types::PCallableType.new(param_types, block_type, return_type) end def internal_type_parse(type_string, loader) Puppet::Pops::Types::TypeParser.singleton.parse(type_string, loader) rescue StandardError => e raise ArgumentError, _("Parsing of type string '\"%{type_string}\"' failed with message: <%{message}>.\n") % { type_string: type_string, message: e.message } end private :internal_type_parse end # The LocalTypeAliasBuilder is used by the 'local_types' method to collect the individual # type aliases given by the function's author. # class LocalTypeAliasesBuilder attr_reader :local_types, :parser, :loader def initialize(loader, name) @loader = Puppet::Pops::Loader::PredefinedLoader.new(loader, :"local_function_#{name}", loader.environment) @local_types = [] # get the shared parser used by puppet's compiler @parser = Puppet::Pops::Parser::EvaluatingParser.singleton() end # Defines a local type alias, the given string should be a Puppet Language type alias expression # in string form without the leading 'type' keyword. # Calls to local_type must be made before the first parameter definition or an error will # be raised. # # @param assignment_string [String] a string on the form 'AliasType = ExistingType' # @api public # def type(assignment_string) # Get location to use in case of error - this produces ruby filename and where call to 'type' occurred # but strips off the rest of the internal "where" as it is not meaningful to user. # rb_location = caller(1, 1).first begin result = parser.parse_string("type #{assignment_string}", nil) rescue StandardError => e rb_location = rb_location.gsub(/:in.*$/, '') # Create a meaningful location for parse errors - show both what went wrong with the parsing # and in which ruby file it was found. raise ArgumentError, _("Parsing of 'type \"%{assignment_string}\"' failed with message: <%{message}>.\n" \ "Called from <%{ruby_file_location}>") % { assignment_string: assignment_string, message: e.message, ruby_file_location: rb_location } end unless result.body.is_a?(Puppet::Pops::Model::TypeAlias) rb_location = rb_location.gsub(/:in.*$/, '') raise ArgumentError, _("Expected a type alias assignment on the form 'AliasType = T', got '%{assignment_string}'.\n" \ "Called from <%{ruby_file_location}>") % { assignment_string: assignment_string, ruby_file_location: rb_location } end @local_types << result.body end end # @note WARNING: This style of creating functions is not public. It is a system # under development that will be used for creating "system" functions. # # This is a private, internal, system for creating functions. It supports # everything that the public function definition system supports as well as a # few extra features such as injection of well known parameters. # # @api private class InternalFunction < Function # @api private def self.builder InternalDispatchBuilder.new(dispatcher, Puppet::Pops::Types::PCallableType::DEFAULT, loader) end # Allows the implementation of a function to call other functions by name and pass the caller # scope. The callable functions are those visible to the same loader that loaded this function # (the calling function). # # @param scope [Puppet::Parser::Scope] The caller scope # @param function_name [String] The name of the function # @param *args [Object] splat of arguments # @return [Object] The result returned by the called function # # @api public def call_function_with_scope(scope, function_name, *args, &block) internal_call_function(scope, function_name, args, &block) end end class Function3x < InternalFunction # Table of optimized parameter names - 0 to 5 parameters PARAM_NAMES = [ [], ['p0'].freeze, %w[p0 p1].freeze, %w[p0 p1 p2].freeze, %w[p0 p1 p2 p3].freeze, %w[p0 p1 p2 p3 p4].freeze ] # Creates an anonymous Function3x class that wraps a 3x function # # @api private def self.create_function(func_name, func_info, loader) func_name = func_name.to_s # Creates an anonymous class to represent the function # The idea being that it is garbage collected when there are no more # references to it. # # (Do not give the class the block here, as instance variables should be set first) the_class = Class.new(Function3x) unless loader.nil? the_class.instance_variable_set(:'@loader', loader.private_loader) end the_class.instance_variable_set(:'@func_name', func_name) the_class.instance_variable_set(:'@method3x', :"function_#{func_name}") # Make the anonymous class appear to have the class-name <func_name> # Even if this class is not bound to such a symbol in a global ruby scope and # must be resolved via the loader. # This also overrides any attempt to define a name method in the given block # (Since it redefines it) # the_class.instance_eval do def name @func_name end def loader @loader end def method3x @method3x end end # Add the method that is called - it simply delegates to # the 3.x function by calling it via the calling scope using the @method3x symbol # :"function_#{name}". # # When function is not an rvalue function, make sure it produces nil # the_class.class_eval do # Bypasses making the call via the dispatcher to make sure errors # are reported exactly the same way as in 3x. The dispatcher is still needed as it is # used to support other features than calling. # def call(scope, *args, &block) result = catch(:return) do mapped_args = Puppet::Pops::Evaluator::Runtime3FunctionArgumentConverter.map_args(args, scope, '') # this is the scope.function_xxx(...) call return scope.send(self.class.method3x, mapped_args) end result.value rescue Puppet::Pops::Evaluator::Next => jumper begin throw :next, jumper.value rescue Puppet::Parser::Scope::UNCAUGHT_THROW_EXCEPTION raise Puppet::ParseError.new("next() from context where this is illegal", jumper.file, jumper.line) end rescue Puppet::Pops::Evaluator::Return => jumper begin throw :return, jumper rescue Puppet::Parser::Scope::UNCAUGHT_THROW_EXCEPTION raise Puppet::ParseError.new("return() from context where this is illegal", jumper.file, jumper.line) end end end # Create a dispatcher based on func_info type, names = Puppet::Functions.any_signature(*from_to_names(func_info)) last_captures_rest = (type.size_range[1] == Float::INFINITY) # The method '3x_function' here is a dummy as the dispatcher is not used for calling, only for information. the_class.dispatcher.add(Puppet::Pops::Functions::Dispatch.new(type, '3x_function', names, last_captures_rest)) # The function class is returned as the result of the create function method the_class end # Compute min and max number of arguments and a list of constructed # parameter names p0 - pn (since there are no parameter names in 3x functions). # # @api private def self.from_to_names(func_info) arity = func_info[:arity] if arity.nil? arity = -1 end if arity < 0 from = -arity - 1 # arity -1 is 0 min param, -2 is min 1 param to = :default # infinite range count = -arity # the number of named parameters else count = from = to = arity end # Names of parameters, up to 5 are optimized and use frozen version # Note that (0..count-1) produces expected empty array for count == 0, 0-n for count >= 1 names = count <= 5 ? PARAM_NAMES[count] : (0..count - 1).map { |n| "p#{n}" } [from, to, names] end end # Injection and Weaving of parameters # --- # It is possible to inject and weave a set of well known parameters into a call. # These extra parameters are not part of the parameters passed from the Puppet # logic, and they can not be overridden by parameters given as arguments in the # call. They are invisible to the Puppet Language. # # @example using injected parameters # Puppet::Functions.create_function('test') do # dispatch :test do # param 'Scalar', 'a' # param 'Scalar', 'b' # scope_param # end # def test(a, b, scope) # a > b ? scope['a'] : scope['b'] # end # end # # The function in the example above is called like this: # # test(10, 20) # # @api private class InternalDispatchBuilder < DispatcherBuilder # Inject parameter for `Puppet::Parser::Scope` def scope_param
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/info_service.rb
lib/puppet/info_service.rb
# frozen_string_literal: true module Puppet::InfoService require_relative 'info_service/class_information_service' require_relative 'info_service/task_information_service' require_relative 'info_service/plan_information_service' def self.classes_per_environment(env_file_hash) Puppet::InfoService::ClassInformationService.new.classes_per_environment(env_file_hash) end def self.tasks_per_environment(environment_name) Puppet::InfoService::TaskInformationService.tasks_per_environment(environment_name) end def self.task_data(environment_name, module_name, task_name) Puppet::InfoService::TaskInformationService.task_data(environment_name, module_name, task_name) end def self.plans_per_environment(environment_name) Puppet::InfoService::PlanInformationService.plans_per_environment(environment_name) end def self.plan_data(environment_name, module_name, plan_name) Puppet::InfoService::PlanInformationService.plan_data(environment_name, module_name, plan_name) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/data_binding.rb
lib/puppet/data_binding.rb
# frozen_string_literal: true require_relative '../puppet/indirector' # A class for managing data lookups class Puppet::DataBinding # Set up indirection, so that data can be looked for in the compiler extend Puppet::Indirector indirects(:data_binding, :terminus_setting => :data_binding_terminus, :doc => "Where to find external data bindings.") class LookupError < Puppet::PreformattedError; end class RecursiveLookupError < Puppet::DataBinding::LookupError; end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/configurer.rb
lib/puppet/configurer.rb
# frozen_string_literal: true # The client for interacting with the puppetmaster config server. require 'timeout' require_relative '../puppet/util' require 'securerandom' # require 'puppet/parser/script_compiler' require_relative '../puppet/pops/evaluator/deferred_resolver' class Puppet::Configurer require_relative 'configurer/fact_handler' require_relative 'configurer/plugin_handler' include Puppet::Configurer::FactHandler # For benchmarking include Puppet::Util attr_reader :environment # Provide more helpful strings to the logging that the Agent does def self.to_s _("Puppet configuration client") end def self.should_pluginsync? if Puppet[:use_cached_catalog] false else true end end def execute_postrun_command execute_from_setting(:postrun_command) end def execute_prerun_command execute_from_setting(:prerun_command) end # Initialize and load storage def init_storage Puppet::Util::Storage.load rescue => detail Puppet.log_exception(detail, _("Removing corrupt state file %{file}: %{detail}") % { file: Puppet[:statefile], detail: detail }) begin Puppet::FileSystem.unlink(Puppet[:statefile]) retry rescue => detail raise Puppet::Error.new(_("Cannot remove %{file}: %{detail}") % { file: Puppet[:statefile], detail: detail }, detail) end end def initialize(transaction_uuid = nil, job_id = nil) @running = false @splayed = false @running_failure = false @cached_catalog_status = 'not_used' @environment = Puppet[:environment] @transaction_uuid = transaction_uuid || SecureRandom.uuid @job_id = job_id @static_catalog = true @checksum_type = Puppet[:supported_checksum_types] @handler = Puppet::Configurer::PluginHandler.new() end # Get the remote catalog, yo. Returns nil if no catalog can be found. def retrieve_catalog(facts, query_options) query_options ||= {} if Puppet[:use_cached_catalog] || @running_failure result = retrieve_catalog_from_cache(query_options) end if result if Puppet[:use_cached_catalog] @cached_catalog_status = 'explicitly_requested' elsif @running_failure @cached_catalog_status = 'on_failure' end Puppet.info _("Using cached catalog from environment '%{environment}'") % { environment: result.environment } else result = retrieve_new_catalog(facts, query_options) unless result unless Puppet[:usecacheonfailure] Puppet.warning _("Not using cache on failed catalog") return nil end result = retrieve_catalog_from_cache(query_options) if result # don't use use cached catalog if it doesn't match server specified environment if result.environment != @environment Puppet.err _("Not using cached catalog because its environment '%{catalog_env}' does not match '%{local_env}'") % { catalog_env: result.environment, local_env: @environment } return nil end @cached_catalog_status = 'on_failure' Puppet.info _("Using cached catalog from environment '%{catalog_env}'") % { catalog_env: result.environment } end end end result end # Convert a plain resource catalog into our full host catalog. def convert_catalog(result, duration, facts, options = {}) catalog = nil catalog_conversion_time = thinmark do # Will mutate the result and replace all Deferred values with resolved values if facts Puppet::Pops::Evaluator::DeferredResolver.resolve_and_replace(facts, result, Puppet.lookup(:current_environment), Puppet[:preprocess_deferred]) end catalog = result.to_ral catalog.finalize catalog.retrieval_duration = duration if Puppet[:write_catalog_summary] catalog.write_class_file catalog.write_resource_file end end options[:report].add_times(:convert_catalog, catalog_conversion_time) if options[:report] catalog end def warn_number_of_facts(size, max_number) Puppet.warning _("The current total number of fact values: %{size} exceeds the fact values limit: %{max_size}") % { size: size, max_size: max_number } end def warn_fact_name_length(name, max_length, fact_name_length) Puppet.warning _("Fact %{name} with length: %{length} exceeds the fact name length limit: %{limit}") % { name: name, length: fact_name_length, limit: max_length } end def warn_number_of_top_level_facts(size, max_number) Puppet.warning _("The current number of top level facts: %{size} exceeds the top facts limit: %{max_size}") % { size: size, max_size: max_number } end def warn_fact_value_length(name, value, max_length) Puppet.warning _("Fact %{name} with value %{value} with the value length: %{length} exceeds the value length limit: %{max_length}") % { name: name, value: value, length: value.to_s.bytesize, max_length: max_length } end def warn_fact_payload_size(payload, max_size) Puppet.warning _("Payload with the current size of: %{payload} exceeds the payload size limit: %{max_size}") % { payload: payload, max_size: max_size } end def check_fact_name_length(fact_path, number_of_dots) max_length = Puppet[:fact_name_length_soft_limit] return if max_length.zero? name_without_dots = fact_path.join() # rough byte size estimations of fact path as a postgresql btree index size_as_btree_index = 8 + (number_of_dots * 2) + name_without_dots.to_s.bytesize warn_fact_name_length(fact_path.join('.'), max_length, size_as_btree_index) if size_as_btree_index > max_length end def check_fact_values_length(name, values) max_length = Puppet[:fact_value_length_soft_limit] return if max_length.zero? warn_fact_value_length(name, values, max_length) if values.to_s.bytesize > max_length end def check_top_level_number_limit(size) max_size = Puppet[:top_level_facts_soft_limit] return if max_size.zero? warn_number_of_top_level_facts(size, max_size) if size > max_size end def check_total_number_limit(size) max_size = Puppet[:number_of_facts_soft_limit] return if max_size.zero? warn_number_of_facts(size, max_size) if size > max_size end def check_payload_size(payload) max_size = Puppet[:payload_soft_limit] return if max_size.zero? warn_fact_payload_size(payload, max_size) if payload > max_size Puppet.debug _("The size of the payload is %{payload}") % { payload: payload } end def parse_fact_name_and_value_limits(object, path = []) case object when Hash object.each do |key, value| path.push(key) parse_fact_name_and_value_limits(value, path) path.pop end when Array object.each_with_index do |e, idx| path.push(idx) parse_fact_name_and_value_limits(e, path) path.pop end else check_fact_name_length(path, path.size) check_fact_values_length(path.join('.'), object) @number_of_facts += 1 end end def check_facts_limits(facts) @number_of_facts = 0 check_top_level_number_limit(facts.size) parse_fact_name_and_value_limits(facts) check_total_number_limit(@number_of_facts) Puppet.debug _("The total number of facts registered is %{number_of_facts}") % { number_of_facts: @number_of_facts } end def get_facts(options) if options[:pluginsync] plugin_sync_time = thinmark do remote_environment_for_plugins = Puppet::Node::Environment.remote(@environment) download_plugins(remote_environment_for_plugins) Puppet::GettextConfig.reset_text_domain('agent') Puppet::ModuleTranslations.load_from_vardir(Puppet[:vardir]) end options[:report].add_times(:plugin_sync, plugin_sync_time) if options[:report] end facts_hash = {} facts = nil if Puppet::Resource::Catalog.indirection.terminus_class == :rest # This is a bit complicated. We need the serialized and escaped facts, # and we need to know which format they're encoded in. Thus, we # get a hash with both of these pieces of information. # # facts_for_uploading may set Puppet[:node_name_value] as a side effect facter_time = thinmark do facts = find_facts check_facts_limits(facts.to_data_hash['values']) facts_hash = encode_facts(facts) # encode for uploading # was: facts_for_uploading check_payload_size(facts_hash[:facts].bytesize) end options[:report].add_times(:fact_generation, facter_time) if options[:report] end [facts_hash, facts] end def prepare_and_retrieve_catalog(cached_catalog, facts, options, query_options) # set report host name now that we have the fact options[:report].host = Puppet[:node_name_value] query_options[:transaction_uuid] = @transaction_uuid query_options[:job_id] = @job_id query_options[:static_catalog] = @static_catalog # Query params don't enforce ordered evaluation, so munge this list into a # dot-separated string. query_options[:checksum_type] = @checksum_type.join('.') # apply passes in ral catalog catalog = cached_catalog || options[:catalog] unless catalog # retrieve_catalog returns resource catalog catalog = retrieve_catalog(facts, query_options) Puppet.err _("Could not retrieve catalog; skipping run") unless catalog end catalog end def prepare_and_retrieve_catalog_from_cache(options = {}) result = retrieve_catalog_from_cache({ :transaction_uuid => @transaction_uuid, :static_catalog => @static_catalog }) Puppet.info _("Using cached catalog from environment '%{catalog_env}'") % { catalog_env: result.environment } if result result end # Apply supplied catalog and return associated application report def apply_catalog(catalog, options) report = options[:report] report.configuration_version = catalog.version benchmark(:notice, _("Applied catalog in %{seconds} seconds")) do apply_catalog_time = thinmark do catalog.apply(options) end options[:report].add_times(:catalog_application, apply_catalog_time) end report end # The code that actually runs the catalog. # This just passes any options on to the catalog, # which accepts :tags and :ignoreschedules. def run(options = {}) # We create the report pre-populated with default settings for # environment and transaction_uuid very early, this is to ensure # they are sent regardless of any catalog compilation failures or # exceptions. options[:report] ||= Puppet::Transaction::Report.new(nil, @environment, @transaction_uuid, @job_id, options[:start_time] || Time.now) report = options[:report] init_storage Puppet::Util::Log.newdestination(report) completed = nil begin # Skip failover logic if the server_list setting is empty do_failover = Puppet.settings[:server_list] && !Puppet.settings[:server_list].empty? # When we are passed a catalog, that means we're in apply # mode. We shouldn't try to do any failover in that case. if options[:catalog].nil? && do_failover server, port = find_functional_server if server.nil? detail = _("Could not select a functional puppet server from server_list: '%{server_list}'") % { server_list: Puppet.settings.value(:server_list, Puppet[:environment].to_sym, true) } if Puppet[:usecacheonfailure] options[:pluginsync] = false @running_failure = true server = Puppet[:server_list].first[0] port = Puppet[:server_list].first[1] || Puppet[:serverport] Puppet.err(detail) else raise Puppet::Error, detail end else # TRANSLATORS 'server_list' is the name of a setting and should not be translated Puppet.debug _("Selected puppet server from the `server_list` setting: %{server}:%{port}") % { server: server, port: port } report.server_used = "#{server}:#{port}" end Puppet.override(server: server, serverport: port) do completed = run_internal(options) end else completed = run_internal(options) end ensure # we may sleep for awhile, close connections now Puppet.runtime[:http].close end completed ? report.exit_status : nil end def run_internal(options) report = options[:report] report.initial_environment = Puppet[:environment] if options[:start_time] startup_time = Time.now - options[:start_time] report.add_times(:startup_time, startup_time) end # If a cached catalog is explicitly requested, attempt to retrieve it. Skip the node request, # don't pluginsync and switch to the catalog's environment if we successfully retrieve it. if Puppet[:use_cached_catalog] Puppet::GettextConfig.reset_text_domain('agent') Puppet::ModuleTranslations.load_from_vardir(Puppet[:vardir]) cached_catalog = prepare_and_retrieve_catalog_from_cache(options) if cached_catalog @cached_catalog_status = 'explicitly_requested' if @environment != cached_catalog.environment && !Puppet[:strict_environment_mode] Puppet.notice _("Local environment: '%{local_env}' doesn't match the environment of the cached catalog '%{catalog_env}', switching agent to '%{catalog_env}'.") % { local_env: @environment, catalog_env: cached_catalog.environment } @environment = cached_catalog.environment end report.environment = @environment else # Don't try to retrieve a catalog from the cache again after we've already # failed to do so the first time. Puppet[:use_cached_catalog] = false Puppet[:usecacheonfailure] = false options[:pluginsync] = Puppet::Configurer.should_pluginsync? end end begin unless Puppet[:node_name_fact].empty? query_options, facts = get_facts(options) end configured_environment = Puppet[:environment] if Puppet.settings.set_by_config?(:environment) # We only need to find out the environment to run in if we don't already have a catalog unless cached_catalog || options[:catalog] || Puppet.settings.set_by_cli?(:environment) || Puppet[:strict_environment_mode] Puppet.debug(_("Environment not passed via CLI and no catalog was given, attempting to find out the last server-specified environment")) initial_environment, loaded_last_environment = last_server_specified_environment unless Puppet[:use_last_environment] && loaded_last_environment Puppet.debug(_("Requesting environment from the server")) initial_environment = current_server_specified_environment(@environment, configured_environment, options) end if initial_environment @environment = initial_environment report.environment = initial_environment push_current_environment_and_loaders else Puppet.debug(_("Could not find a usable environment in the lastrunfile. Either the file does not exist, does not have the required keys, or the values of 'initial_environment' and 'converged_environment' are identical.")) end end Puppet.info _("Using environment '%{env}'") % { env: @environment } # This is to maintain compatibility with anyone using this class # aside from agent, apply, device. unless Puppet.lookup(:loaders) { nil } push_current_environment_and_loaders end temp_value = options[:pluginsync] # only validate server environment if pluginsync is requested options[:pluginsync] = valid_server_environment? if options[:pluginsync] query_options, facts = get_facts(options) unless query_options options[:pluginsync] = temp_value query_options[:configured_environment] = configured_environment catalog = prepare_and_retrieve_catalog(cached_catalog, facts, options, query_options) unless catalog return nil end if Puppet[:strict_environment_mode] && catalog.environment != @environment Puppet.err _("Not using catalog because its environment '%{catalog_env}' does not match agent specified environment '%{local_env}' and strict_environment_mode is set") % { catalog_env: catalog.environment, local_env: @environment } return nil end # Here we set the local environment based on what we get from the # catalog. Since a change in environment means a change in facts, and # facts may be used to determine which catalog we get, we need to # rerun the process if the environment is changed. tries = 0 while catalog.environment and !catalog.environment.empty? and catalog.environment != @environment if tries > 3 raise Puppet::Error, _("Catalog environment didn't stabilize after %{tries} fetches, aborting run") % { tries: tries } end Puppet.notice _("Local environment: '%{local_env}' doesn't match server specified environment '%{catalog_env}', restarting agent run with environment '%{catalog_env}'") % { local_env: @environment, catalog_env: catalog.environment } @environment = catalog.environment report.environment = @environment push_current_environment_and_loaders query_options, facts = get_facts(options) query_options[:configured_environment] = configured_environment # if we get here, ignore the cached catalog catalog = prepare_and_retrieve_catalog(nil, facts, options, query_options) return nil unless catalog tries += 1 end # now that environment has converged, convert resource catalog into ral catalog # unless we were given a RAL catalog if !cached_catalog && options[:catalog] ral_catalog = options[:catalog] else # Ordering here matters. We have to resolve deferred resources in the # resource catalog, convert the resource catalog to a RAL catalog (which # triggers type/provider validation), and only if that is successful, # should we cache the *original* resource catalog. However, deferred # evaluation mutates the resource catalog, so we need to make a copy of # it here. If PUP-9323 is ever implemented so that we resolve deferred # resources in the RAL catalog as they are needed, then we could eliminate # this step. catalog_to_cache = Puppet.override(:rich_data => Puppet[:rich_data]) do Puppet::Resource::Catalog.from_data_hash(catalog.to_data_hash) end # REMIND @duration is the time spent loading the last catalog, and doesn't # account for things like we failed to download and fell back to the cache ral_catalog = convert_catalog(catalog, @duration, facts, options) # Validation succeeded, so commit the `catalog_to_cache` for non-noop runs. Don't # commit `catalog` since it contains the result of deferred evaluation. Ideally # we'd just copy the downloaded response body, instead of serializing the # in-memory catalog, but that's hard due to the indirector. indirection = Puppet::Resource::Catalog.indirection if !Puppet[:noop] && indirection.cache? request = indirection.request(:save, nil, catalog_to_cache, environment: Puppet::Node::Environment.remote(catalog_to_cache.environment)) Puppet.info("Caching catalog for #{request.key}") indirection.cache.save(request) end end execute_prerun_command or return nil options[:report].code_id = ral_catalog.code_id options[:report].catalog_uuid = ral_catalog.catalog_uuid options[:report].cached_catalog_status = @cached_catalog_status apply_catalog(ral_catalog, options) true rescue => detail Puppet.log_exception(detail, _("Failed to apply catalog: %{detail}") % { detail: detail }) nil ensure execute_postrun_command or return nil # rubocop:disable Lint/EnsureReturn end ensure if Puppet[:resubmit_facts] # TODO: Should mark the report as "failed" if an error occurs and # resubmit_facts returns false. There is currently no API for this. resubmit_facts_time = thinmark { resubmit_facts } report.add_times(:resubmit_facts, resubmit_facts_time) end report.cached_catalog_status ||= @cached_catalog_status report.add_times(:total, Time.now - report.time) report.finalize_report Puppet::Util::Log.close(report) send_report(report) Puppet.pop_context end private :run_internal def valid_server_environment? session = Puppet.lookup(:http_session) begin fs = session.route_to(:fileserver) fs.get_file_metadatas(path: URI(Puppet[:pluginsource]).path, recurse: :false, environment: @environment) # rubocop:disable Lint/BooleanSymbol true rescue Puppet::HTTP::ResponseError => detail if detail.response.code == 404 if Puppet[:strict_environment_mode] raise Puppet::Error, _("Environment '%{environment}' not found on server, aborting run.") % { environment: @environment } else Puppet.notice(_("Environment '%{environment}' not found on server, skipping initial pluginsync.") % { environment: @environment }) end else Puppet.log_exception(detail, detail.message) end false rescue => detail Puppet.log_exception(detail, detail.message) false end end def find_functional_server begin session = Puppet.lookup(:http_session) service = session.route_to(:puppet) return [service.url.host, service.url.port] rescue Puppet::HTTP::ResponseError => e Puppet.debug(_("Puppet server %{host}:%{port} is unavailable: %{code} %{reason}") % { host: e.response.url.host, port: e.response.url.port, code: e.response.code, reason: e.response.reason }) rescue => detail # TRANSLATORS 'server_list' is the name of a setting and should not be translated Puppet.debug _("Unable to connect to server from server_list setting: %{detail}") % { detail: detail } end [nil, nil] end private :find_functional_server # # @api private # # Read the last server-specified environment from the lastrunfile. The # environment is considered to be server-specified if the values of # `initial_environment` and `converged_environment` are different. # # @return [String, Boolean] An array containing a string with the environment # read from the lastrunfile in case the server is authoritative, and a # boolean marking whether the last environment was correctly loaded. def last_server_specified_environment return @last_server_specified_environment, @loaded_last_environment if @last_server_specified_environment if Puppet::FileSystem.exist?(Puppet[:lastrunfile]) summary = Puppet::Util::Yaml.safe_load_file(Puppet[:lastrunfile]) return [nil, nil] unless summary['application']['run_mode'] == 'agent' initial_environment = summary['application']['initial_environment'] converged_environment = summary['application']['converged_environment'] @last_server_specified_environment = converged_environment if initial_environment != converged_environment Puppet.debug(_("Successfully loaded last environment from the lastrunfile")) @loaded_last_environment = true end Puppet.debug(_("Found last server-specified environment: %{environment}") % { environment: @last_server_specified_environment }) if @last_server_specified_environment [@last_server_specified_environment, @loaded_last_environment] rescue => detail Puppet.debug(_("Could not find last server-specified environment: %{detail}") % { detail: detail }) [nil, nil] end private :last_server_specified_environment def current_server_specified_environment(current_environment, configured_environment, options) return @server_specified_environment if @server_specified_environment begin node_retr_time = thinmark do node = Puppet::Node.indirection.find(Puppet[:node_name_value], :environment => Puppet::Node::Environment.remote(current_environment), :configured_environment => configured_environment, :ignore_cache => true, :transaction_uuid => @transaction_uuid, :fail_on_404 => true) @server_specified_environment = node.environment_name.to_s if @server_specified_environment != @environment Puppet.notice _("Local environment: '%{local_env}' doesn't match server specified node environment '%{node_env}', switching agent to '%{node_env}'.") % { local_env: @environment, node_env: @server_specified_environment } end end options[:report].add_times(:node_retrieval, node_retr_time) @server_specified_environment rescue => detail Puppet.warning(_("Unable to fetch my node definition, but the agent run will continue:")) Puppet.warning(detail) nil end end private :current_server_specified_environment def send_report(report) puts report.summary if Puppet[:summarize] save_last_run_summary(report) if Puppet[:report] remote = Puppet::Node::Environment.remote(@environment) begin Puppet::Transaction::Report.indirection.save(report, nil, ignore_cache: true, environment: remote) ensure Puppet::Transaction::Report.indirection.save(report, nil, ignore_terminus: true, environment: remote) end end rescue => detail Puppet.log_exception(detail, _("Could not send report: %{detail}") % { detail: detail }) end def save_last_run_summary(report) mode = Puppet.settings.setting(:lastrunfile).mode Puppet::Util.replace_file(Puppet[:lastrunfile], mode) do |fh| fh.print YAML.dump(report.raw_summary) end rescue => detail Puppet.log_exception(detail, _("Could not save last run local report: %{detail}") % { detail: detail }) end # Submit updated facts to the Puppet Server # # This method will clear all current fact values, load a fresh set of # fact data, and then submit it to the Puppet Server. # # @return [true] If fact submission succeeds. # @return [false] If an exception is raised during fact generation or # submission. def resubmit_facts Puppet.runtime[:facter].clear facts = find_facts client = Puppet.runtime[:http] session = client.create_session puppet = session.route_to(:puppet) Puppet.info(_("Uploading facts for %{node} to %{server}") % { node: facts.name, server: puppet.url.hostname }) puppet.put_facts(facts.name, facts: facts, environment: Puppet.lookup(:current_environment).name.to_s) true rescue => detail Puppet.log_exception(detail, _("Failed to submit facts: %{detail}") % { detail: detail }) false end private def execute_from_setting(setting) return true if (command = Puppet[setting]) == "" begin Puppet::Util::Execution.execute([command]) true rescue => detail Puppet.log_exception(detail, _("Could not run command from %{setting}: %{detail}") % { setting: setting, detail: detail }) false end end def push_current_environment_and_loaders new_env = Puppet::Node::Environment.remote(@environment) Puppet.push_context( { :current_environment => new_env, :loaders => Puppet::Pops::Loaders.new(new_env, true) }, "Local node environment #{@environment} for configurer transaction" ) end def retrieve_catalog_from_cache(query_options) result = nil @duration = thinmark do result = Puppet::Resource::Catalog.indirection.find( Puppet[:node_name_value], query_options.merge( :ignore_terminus => true, :environment => Puppet::Node::Environment.remote(@environment) ) ) end result rescue => detail Puppet.log_exception(detail, _("Could not retrieve catalog from cache: %{detail}") % { detail: detail }) nil end def retrieve_new_catalog(facts, query_options) result = nil @duration = thinmark do result = Puppet::Resource::Catalog.indirection.find( Puppet[:node_name_value], query_options.merge( :ignore_cache => true, # don't update cache until after environment converges :ignore_cache_save => true, :environment => Puppet::Node::Environment.remote(@environment), :check_environment => true, :fail_on_404 => true, :facts_for_catalog => facts ) ) end result rescue StandardError => detail Puppet.log_exception(detail, _("Could not retrieve catalog from remote server: %{detail}") % { detail: detail }) nil end def download_plugins(remote_environment_for_plugins) @handler.download_plugins(remote_environment_for_plugins) rescue Puppet::Error => detail if !Puppet[:ignore_plugin_errors] && Puppet[:usecacheonfailure] @running_failure = true else raise detail end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application_support.rb
lib/puppet/application_support.rb
# frozen_string_literal: true require 'yaml' require_relative '../puppet' require_relative '../puppet/node/environment' require_relative '../puppet/file_system' require_relative '../puppet/indirector' module Puppet module ApplicationSupport # Pushes a Puppet Context configured with a remote environment for an agent # (one that exists at the master end), and a regular environment for other # modes. The configuration is overridden with options from the command line # before being set in a pushed Puppet Context. # # @param run_mode [Puppet::Util::RunMode] Puppet's current Run Mode. # @param environment_mode [Symbol] optional, Puppet's # current Environment Mode. Defaults to :local # @return [void] # @api private def self.push_application_context(run_mode, environment_mode = :local) Puppet.push_context_global(Puppet.base_context(Puppet.settings), "Update for application settings (#{run_mode})") # This use of configured environment is correct, this is used to establish # the defaults for an application that does not override, or where an override # has not been made from the command line. # configured_environment_name = Puppet[:environment] if run_mode.name == :agent configured_environment = Puppet::Node::Environment.remote(configured_environment_name) elsif environment_mode == :not_required configured_environment = Puppet.lookup(:environments).get(configured_environment_name) || Puppet::Node::Environment.remote(configured_environment_name) else configured_environment = Puppet.lookup(:environments).get!(configured_environment_name) end configured_environment = configured_environment.override_from_commandline(Puppet.settings) # Setup a new context using the app's configuration Puppet.push_context({ :current_environment => configured_environment }, "Update current environment from application's configuration") end # Reads the routes YAML settings from the file specified by Puppet[:route_file] # and resets indirector termini for the current application class if listed. # # For instance, PE uses this to set the master facts terminus # to 'puppetdb' and its cache terminus to 'yaml'. # # @param application_name [String] The name of the current application. # @return [void] # @api private def self.configure_indirector_routes(application_name) route_file = Puppet[:route_file] if Puppet::FileSystem.exist?(route_file) routes = Puppet::Util::Yaml.safe_load_file(route_file, [Symbol]) if routes["server"] && routes["master"] Puppet.warning("Route file #{route_file} contains both server and master route settings.") elsif routes["server"] && !routes["master"] routes["master"] = routes["server"] elsif routes["master"] && !routes["server"] routes["server"] = routes["master"] end application_routes = routes[application_name] Puppet::Indirector.configure_routes(application_routes) if application_routes end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/error.rb
lib/puppet/error.rb
# frozen_string_literal: true module Puppet # The base class for all Puppet errors. It can wrap another exception class Error < RuntimeError attr_accessor :original def initialize(message, original = nil) super(message.scrub) @original = original end end module ExternalFileError # This module implements logging with a filename and line number. Use this # for errors that need to report a location in a non-ruby file that we # parse. attr_accessor :line, :file, :pos, :puppetstack # May be called with 3 arguments for message, file, line, and exception, or # 4 args including the position on the line. # def initialize(message, file = nil, line = nil, pos = nil, original = nil) if pos.is_a? Exception original = pos pos = nil end super(message, original) @file = file unless file.is_a?(String) && file.empty? @line = line @pos = pos if original && original.respond_to?(:puppetstack) @puppetstack = original.puppetstack else @puppetstack = Puppet::Pops::PuppetStack.stacktrace() end end def to_s msg = super @file = nil if @file.is_a?(String) && @file.empty? msg += Puppet::Util::Errors.error_location_with_space(@file, @line, @pos) msg end end class ParseError < Puppet::Error include ExternalFileError end class ResourceError < Puppet::Error include ExternalFileError end # Contains an issue code and can be annotated with an environment and a node class ParseErrorWithIssue < Puppet::ParseError attr_reader :issue_code, :basic_message, :arguments attr_accessor :environment, :node # @param message [String] The error message # @param file [String] The path to the file where the error was found # @param line [Integer] The line in the file # @param pos [Integer] The position on the line # @param original [Exception] Original exception # @param issue_code [Symbol] The issue code # @param arguments [Hash{Symbol=>Object}] Issue arguments # def initialize(message, file = nil, line = nil, pos = nil, original = nil, issue_code = nil, arguments = nil) super(message, file, line, pos, original) @issue_code = issue_code @basic_message = message @arguments = arguments end def to_s msg = super msg = _("Could not parse for environment %{environment}: %{message}") % { environment: environment, message: msg } if environment msg = _("%{message} on node %{node}") % { message: msg, node: node } if node msg end def to_h { :issue_code => issue_code, :message => basic_message, :full_message => to_s, :file => file, :line => line, :pos => pos, :environment => environment.to_s, :node => node.to_s, } end def self.from_issue_and_stack(issue, args = {}) filename, line = Puppet::Pops::PuppetStack.top_of_stack new( issue.format(args), filename, line, nil, nil, issue.issue_code, args ) end end # An error that already contains location information in the message text class PreformattedError < Puppet::ParseErrorWithIssue end # An error class for when I don't know what happened. Automatically # prints a stack trace when in debug mode. class DevError < Puppet::Error include ExternalFileError end class MissingCommand < Puppet::Error end # Raised when we failed to acquire a lock class LockError < Puppet::Error end # An Error suitable for raising an error with details in a Puppet::Datatypes::Error # that can be used as a value in the Puppet Language # class ErrorWithData < Puppet::Error include ExternalFileError attr_reader :error_data def initialize(error_data, message, file: nil, line: nil, pos: nil, original: nil) super(message, file, line, pos, original) @error_data = error_data end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector.rb
lib/puppet/indirector.rb
# frozen_string_literal: true # Manage indirections to termini. They are organized in terms of indirections - # - e.g., configuration, node, file, certificate -- and each indirection has one # or more terminus types defined. The indirection is configured via the # +indirects+ method, which will be called by the class extending itself # with this module. module Puppet::Indirector # LAK:FIXME We need to figure out how to handle documentation for the # different indirection types. require_relative 'indirector/indirection' require_relative 'indirector/terminus' require_relative 'indirector/code' require_relative 'indirector/envelope' require_relative '../puppet/network/format_support' def self.configure_routes(application_routes) application_routes.each do |indirection_name, termini| indirection_name = indirection_name.to_sym terminus_name = termini["terminus"] cache_name = termini["cache"] Puppet::Indirector::Terminus.terminus_class(indirection_name, terminus_name || cache_name) indirection = Puppet::Indirector::Indirection.instance(indirection_name) raise _("Indirection %{indirection_name} does not exist") % { indirection_name: indirection_name } unless indirection indirection.set_global_setting(:terminus_class, terminus_name) if terminus_name indirection.set_global_setting(:cache_class, cache_name) if cache_name end end # Declare that the including class indirects its methods to # this terminus. The terminus name must be the name of a Puppet # default, not the value -- if it's the value, then it gets # evaluated at parse time, which is before the user has had a chance # to override it. def indirects(indirection, options = {}) raise(ArgumentError, _("Already handling indirection for %{current}; cannot also handle %{next}") % { current: @indirection.name, next: indirection }) if @indirection # populate this class with the various new methods extend ClassMethods include Puppet::Indirector::Envelope include Puppet::Network::FormatSupport # record the indirected class name for documentation purposes options[:indirected_class] = name # instantiate the actual Terminus for that type and this name (:ldap, w/ args :node) # & hook the instantiated Terminus into this class (Node: @indirection = terminus) @indirection = Puppet::Indirector::Indirection.new(self, indirection, **options) end module ClassMethods attr_reader :indirection end # Helper definition for indirections that handle filenames. BadNameRegexp = Regexp.union(/^\.\./, %r{[\\/]}, "\0", /(?i)^[a-z]:/) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops.rb
lib/puppet/pops.rb
# frozen_string_literal: true module Puppet # The Pops language system. This includes the parser, evaluator, AST model, and # Binder. # # @todo Explain how a user should use this to parse and evaluate the puppet # language. # # @note Warning: Pops is still considered experimental, as such the API may # change at any time. # # @api public module Pops EMPTY_HASH = {}.freeze EMPTY_ARRAY = [].freeze EMPTY_STRING = '' MAX_INTEGER = 0x7fffffffffffffff MIN_INTEGER = -0x8000000000000000 DOUBLE_COLON = '::' USCORE = '_' require 'semantic_puppet' require_relative 'pops/patterns' require_relative 'pops/utils' require_relative 'pops/puppet_stack' require_relative 'pops/adaptable' require_relative 'pops/adapters' require_relative 'pops/visitable' require_relative 'pops/visitor' require_relative 'pops/issues' require_relative 'pops/semantic_error' require_relative 'pops/label_provider' require_relative 'pops/validation' require_relative 'pops/issue_reporter' require_relative 'pops/time/timespan' require_relative 'pops/time/timestamp' # (the Types module initializes itself) require_relative 'pops/types/types' require_relative 'pops/types/string_converter' require_relative 'pops/lookup' require_relative 'pops/merge_strategy' module Model require_relative 'pops/model/ast' require_relative 'pops/model/tree_dumper' require_relative 'pops/model/ast_transformer' require_relative 'pops/model/factory' require_relative 'pops/model/model_tree_dumper' require_relative 'pops/model/model_label_provider' end module Resource require_relative 'pops/resource/resource_type_impl' end module Evaluator require_relative 'pops/evaluator/literal_evaluator' require_relative 'pops/evaluator/callable_signature' require_relative 'pops/evaluator/runtime3_converter' require_relative 'pops/evaluator/runtime3_resource_support' require_relative 'pops/evaluator/runtime3_support' require_relative 'pops/evaluator/evaluator_impl' require_relative 'pops/evaluator/epp_evaluator' require_relative 'pops/evaluator/collector_transformer' require_relative 'pops/evaluator/puppet_proc' require_relative 'pops/evaluator/deferred_resolver' module Collectors require_relative 'pops/evaluator/collectors/abstract_collector' require_relative 'pops/evaluator/collectors/fixed_set_collector' require_relative 'pops/evaluator/collectors/catalog_collector' require_relative 'pops/evaluator/collectors/exported_collector' end end module Parser require_relative 'pops/parser/eparser' require_relative 'pops/parser/parser_support' require_relative 'pops/parser/locator' require_relative 'pops/parser/locatable' require_relative 'pops/parser/lexer2' require_relative 'pops/parser/evaluating_parser' require_relative 'pops/parser/epp_parser' require_relative 'pops/parser/code_merger' end module Validation require_relative 'pops/validation/checker4_0' require_relative 'pops/validation/validator_factory_4_0' end # Subsystem for puppet functions defined in ruby. # # @api public module Functions require_relative 'pops/functions/function' require_relative 'pops/functions/dispatch' require_relative 'pops/functions/dispatcher' end module Migration require_relative 'pops/migration/migration_checker' end module Serialization require_relative 'pops/serialization' end end require_relative '../puppet/parser/ast/pops_bridge' require_relative '../puppet/functions' require_relative '../puppet/datatypes' Puppet::Pops::Model.register_pcore_types end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util.rb
lib/puppet/util.rb
# frozen_string_literal: true # A module to collect utility functions. require 'English' require_relative '../puppet/error' require_relative 'util/execution_stub' require 'uri' require 'pathname' require 'ostruct' require_relative 'util/platform' require_relative 'util/windows' require_relative 'util/symbolic_file_mode' require_relative '../puppet/file_system/uniquefile' require 'securerandom' require_relative 'util/character_encoding' module Puppet module Util require_relative 'util/monkey_patches' require 'benchmark' # These are all for backward compatibility -- these are methods that used # to be in Puppet::Util but have been moved into external modules. require_relative 'util/posix' extend Puppet::Util::POSIX require_relative 'util/windows/process' if Puppet::Util::Platform.windows? extend Puppet::Util::SymbolicFileMode def default_env Puppet.features.microsoft_windows? ? :windows : :posix end module_function :default_env def create_erb(content) ERB.new(content, trim_mode: '-') end module_function :create_erb # @deprecated Use ENV instead # @api private def get_env(name, mode = default_env) ENV.fetch(name, nil) end module_function :get_env # @deprecated Use ENV instead # @api private def get_environment(mode = default_env) ENV.to_hash end module_function :get_environment # @deprecated Use ENV instead # @api private def clear_environment(mode = default_env) ENV.clear end module_function :clear_environment # @deprecated Use ENV instead # @api private def set_env(name, value = nil, mode = default_env) ENV[name] = value end module_function :set_env # @deprecated Use ENV instead # @api private def merge_environment(env_hash, mode = default_env) ENV.merge!(hash.transform_keys(&:to_s)) end module_function :merge_environment # Run some code with a specific environment. Resets the environment back to # what it was at the end of the code. # # @param hash [Hash{String,Symbol => String}] Environment variables to override the current environment. # @param mode [Symbol] ignored def withenv(hash, mode = :posix) saved = ENV.to_hash begin ENV.merge!(hash.transform_keys(&:to_s)) yield ensure ENV.replace(saved) end end module_function :withenv # Execute a given chunk of code with a new umask. def self.withumask(mask) cur = File.umask(mask) begin yield ensure File.umask(cur) end end # Change the process to a different user def self.chuser group = Puppet[:group] if group begin Puppet::Util::SUIDManager.change_group(group, true) rescue => detail Puppet.warning _("could not change to group %{group}: %{detail}") % { group: group.inspect, detail: detail } $stderr.puts _("could not change to group %{group}") % { group: group.inspect } # Don't exit on failed group changes, since it's # not fatal # exit(74) end end user = Puppet[:user] if user begin Puppet::Util::SUIDManager.change_user(user, true) rescue => detail $stderr.puts _("Could not change to user %{user}: %{detail}") % { user: user, detail: detail } exit(74) end end end # Create instance methods for each of the log levels. This allows # the messages to be a little richer. Most classes will be calling this # method. def self.logmethods(klass, useself = true) Puppet::Util::Log.eachlevel { |level| klass.send(:define_method, level, proc { |args| args = args.join(" ") if args.is_a?(Array) if useself Puppet::Util::Log.create( :level => level, :source => self, :message => args ) else Puppet::Util::Log.create( :level => level, :message => args ) end }) } end # execute a block of work and based on the logging level provided, log the provided message with the seconds taken # The message 'msg' should include string ' in %{seconds} seconds' as part of the message and any content should escape # any percent signs '%' so that they are not interpreted as formatting commands # escaped_str = str.gsub(/%/, '%%') # # @param msg [String] the message to be formated to assigned the %{seconds} seconds take to execute, # other percent signs '%' need to be escaped # @param level [Symbol] the logging level for this message # @param object [Object] The object use for logging the message def benchmark(*args) msg = args.pop level = args.pop object = if args.empty? if respond_to?(level) self else Puppet end else args.pop end # TRANSLATORS 'benchmark' is a method name and should not be translated raise Puppet::DevError, _("Failed to provide level to benchmark") unless level unless level == :none or object.respond_to? level raise Puppet::DevError, _("Benchmarked object does not respond to %{value}") % { value: level } end # Only benchmark if our log level is high enough if level != :none and Puppet::Util::Log.sendlevel?(level) seconds = Benchmark.realtime { yield } object.send(level, msg % { seconds: "%0.2f" % seconds }) seconds else yield end end module_function :benchmark # Resolve a path for an executable to the absolute path. This tries to behave # in the same manner as the unix `which` command and uses the `PATH` # environment variable. # # @api public # @param bin [String] the name of the executable to find. # @return [String] the absolute path to the found executable. def which(bin) if absolute_path?(bin) return bin if FileTest.file? bin and FileTest.executable? bin else exts = ENV.fetch('PATHEXT', nil) exts = exts ? exts.split(File::PATH_SEPARATOR) : %w[.COM .EXE .BAT .CMD] ENV.fetch('PATH').split(File::PATH_SEPARATOR).each do |dir| dest = File.expand_path(File.join(dir, bin)) rescue ArgumentError => e # if the user's PATH contains a literal tilde (~) character and HOME is not set, we may get # an ArgumentError here. Let's check to see if that is the case; if not, re-raise whatever error # was thrown. if e.to_s =~ /HOME/ and (ENV['HOME'].nil? || ENV.fetch('HOME', nil) == "") # if we get here they have a tilde in their PATH. We'll issue a single warning about this and then # ignore this path element and carry on with our lives. # TRANSLATORS PATH and HOME are environment variables and should not be translated Puppet::Util::Warnings.warnonce(_("PATH contains a ~ character, and HOME is not set; ignoring PATH element '%{dir}'.") % { dir: dir }) elsif e.to_s =~ /doesn't exist|can't find user/ # ...otherwise, we just skip the non-existent entry, and do nothing. # TRANSLATORS PATH is an environment variable and should not be translated Puppet::Util::Warnings.warnonce(_("Couldn't expand PATH containing a ~ character; ignoring PATH element '%{dir}'.") % { dir: dir }) else raise end else if Puppet::Util::Platform.windows? && File.extname(dest).empty? exts.each do |ext| destext = File.expand_path(dest + ext) return destext if FileTest.file? destext and FileTest.executable? destext end end return dest if FileTest.file? dest and FileTest.executable? dest end end nil end module_function :which # Determine in a platform-specific way whether a path is absolute. This # defaults to the local platform if none is specified. # # Escape once for the string literal, and once for the regex. slash = '[\\\\/]' label = '[^\\\\/]+' AbsolutePathWindows = /^(?:(?:[A-Z]:#{slash})|(?:#{slash}#{slash}#{label}#{slash}#{label})|(?:#{slash}#{slash}\?#{slash}#{label}))/io AbsolutePathPosix = %r{^/} def absolute_path?(path, platform = nil) unless path.is_a?(String) Puppet.warning("Cannot check if #{path} is an absolute path because it is a '#{path.class}' and not a String'") return false end # Ruby only sets File::ALT_SEPARATOR on Windows and the Ruby standard # library uses that to test what platform it's on. Normally in Puppet we # would use Puppet.features.microsoft_windows?, but this method needs to # be called during the initialization of features so it can't depend on # that. # # @deprecated Use ruby's built-in methods to determine if a path is absolute. platform ||= Puppet::Util::Platform.windows? ? :windows : :posix regex = case platform when :windows AbsolutePathWindows when :posix AbsolutePathPosix else raise Puppet::DevError, _("unknown platform %{platform} in absolute_path") % { platform: platform } end !!(path =~ regex) end module_function :absolute_path? # Convert a path to a file URI def path_to_uri(path) return unless path params = { :scheme => 'file' } if Puppet::Util::Platform.windows? path = path.tr('\\', '/') unc = %r{^//([^/]+)(/.+)}.match(path) if unc params[:host] = unc[1] path = unc[2] elsif path =~ %r{^[a-z]:/}i path = '/' + path end end # have to split *after* any relevant escaping params[:path], params[:query] = uri_encode(path).split('?') search_for_fragment = params[:query] ? :query : :path if params[search_for_fragment].include?('#') params[search_for_fragment], _, params[:fragment] = params[search_for_fragment].rpartition('#') end begin URI::Generic.build(params) rescue => detail raise Puppet::Error, _("Failed to convert '%{path}' to URI: %{detail}") % { path: path, detail: detail }, detail.backtrace end end module_function :path_to_uri # Get the path component of a URI def uri_to_path(uri) return unless uri.is_a?(URI) # CGI.unescape doesn't handle space rules properly in uri paths # URI.unescape does, but returns strings in their original encoding path = uri_unescape(uri.path.encode(Encoding::UTF_8)) if Puppet::Util::Platform.windows? && uri.scheme == 'file' if uri.host && !uri.host.empty? path = "//#{uri.host}" + path # UNC else path.sub!(%r{^/}, '') end end path end module_function :uri_to_path RFC_3986_URI_REGEX = %r{^(?<scheme>(?:[^:/?#]+):)?(?<authority>//(?:[^/?#]*))?(?<path>[^?#]*)(?:\?(?<query>[^#]*))?(?:#(?<fragment>.*))?$} # Percent-encodes a URI query parameter per RFC3986 - https://tools.ietf.org/html/rfc3986 # # The output will correctly round-trip through URI.unescape # # @param [String query_string] A URI query parameter that may contain reserved # characters that must be percent encoded for the key or value to be # properly decoded as part of a larger query string: # # query # encodes as : query # # query_with_special=chars like&and * and# plus+this # encodes as: # query_with_special%3Dchars%20like%26and%20%2A%20and%23%20plus%2Bthis # # Note: Also usable by fragments, but not suitable for paths # # @return [String] a new string containing an encoded query string per the # rules of RFC3986. # # In particular, # query will encode + as %2B and space as %20 def uri_query_encode(query_string) return nil if query_string.nil? # query can encode space to %20 OR + # + MUST be encoded as %2B # in RFC3968 both query and fragment are defined as: # = *( pchar / "/" / "?" ) # CGI.escape turns space into + which is the most backward compatible # however it doesn't roundtrip through URI.unescape which prefers %20 CGI.escape(query_string).gsub('+', '%20') end module_function :uri_query_encode # Percent-encodes a URI string per RFC3986 - https://tools.ietf.org/html/rfc3986 # # Properly handles escaping rules for paths, query strings and fragments # independently # # The output is safe to pass to URI.parse or URI::Generic.build and will # correctly round-trip through URI.unescape # # @param [String path] A URI string that may be in the form of: # # http://foo.com/bar?query # file://tmp/foo bar # //foo.com/bar?query # /bar?query # bar?query # bar # . # C:\Windows\Temp # # Note that with no specified scheme, authority or query parameter delimiter # ? that a naked string will be treated as a path. # # Note that if query parameters need to contain data such as & or = # that this method should not be used, as there is no way to differentiate # query parameter data from query delimiters when multiple parameters # are specified # # @param [Hash{Symbol=>String} opts] Options to alter encoding # @option opts [Array<Symbol>] :allow_fragment defaults to false. When false # will treat # as part of a path or query and not a fragment delimiter # # @return [String] a new string containing appropriate portions of the URI # encoded per the rules of RFC3986. # In particular, # path will not encode +, but will encode space as %20 # query will encode + as %2B and space as %20 # fragment behaves like query def uri_encode(path, opts = { :allow_fragment => false }) raise ArgumentError, _('path may not be nil') if path.nil? encoded = ''.dup # parse uri into named matches, then reassemble properly encoded parts = path.match(RFC_3986_URI_REGEX) encoded += parts[:scheme] unless parts[:scheme].nil? encoded += parts[:authority] unless parts[:authority].nil? # path requires space to be encoded as %20 (NEVER +) # + should be left unencoded # URI::parse and URI::Generic.build don't like paths encoded with CGI.escape # URI.escape does not change / to %2F and : to %3A like CGI.escape # encoded += rfc2396_escape(parts[:path]) unless parts[:path].nil? # each query parameter unless parts[:query].nil? query_string = parts[:query].split('&').map do |pair| # can optionally be separated by an = pair.split('=').map do |v| uri_query_encode(v) end.join('=') end.join('&') encoded += '?' + query_string end encoded += ((opts[:allow_fragment] ? '#' : '%23') + uri_query_encode(parts[:fragment])) unless parts[:fragment].nil? encoded end module_function :uri_encode # From https://github.com/ruby/ruby/blob/v2_7_3/lib/uri/rfc2396_parser.rb#L24-L46 ALPHA = "a-zA-Z" ALNUM = "#{ALPHA}\\d" UNRESERVED = "\\-_.!~*'()#{ALNUM}" RESERVED = ";/?:@&=+$,\\[\\]" UNSAFE = Regexp.new("[^#{UNRESERVED}#{RESERVED}]").freeze HEX = "a-fA-F\\d" ESCAPED = Regexp.new("%[#{HEX}]{2}").freeze def rfc2396_escape(str) str.gsub(UNSAFE) do |match| tmp = ''.dup match.each_byte do |uc| tmp << sprintf('%%%02X', uc) end tmp end.force_encoding(Encoding::US_ASCII) end module_function :rfc2396_escape def uri_unescape(str) enc = str.encoding enc = Encoding::UTF_8 if enc == Encoding::US_ASCII str.gsub(ESCAPED) { [::Regexp.last_match(0)[1, 2]].pack('H2').force_encoding(enc) } end module_function :uri_unescape def safe_posix_fork(stdin = $stdin, stdout = $stdout, stderr = $stderr, &block) Kernel.fork do STDIN.reopen(stdin) STDOUT.reopen(stdout) STDERR.reopen(stderr) $stdin = STDIN $stdout = STDOUT $stderr = STDERR begin Dir.foreach('/proc/self/fd') do |f| if f != '.' && f != '..' && f.to_i >= 3 begin IO.new(f.to_i).close rescue nil end end end rescue Errno::ENOENT, Errno::ENOTDIR # /proc/self/fd not found, /proc/self not a dir 3.upto(256) { |fd| begin IO.new(fd).close rescue nil end } end block.call if block end end module_function :safe_posix_fork def symbolizehash(hash) newhash = {} hash.each do |name, val| name = name.intern if name.respond_to? :intern newhash[name] = val end newhash end module_function :symbolizehash # Just benchmark, with no logging. def thinmark Benchmark.realtime { yield } end module_function :thinmark PUPPET_STACK_INSERTION_FRAME = /.*puppet_stack\.rb.*in.*`stack'/ # utility method to get the current call stack and format it to a human-readable string (which some IDEs/editors # will recognize as links to the line numbers in the trace) def self.pretty_backtrace(backtrace = caller(1), puppetstack = []) format_backtrace_array(backtrace, puppetstack).join("\n") end # arguments may be a Ruby stack, with an optional Puppet stack argument, # or just a Puppet stack. # stacks may be an Array of Strings "/foo.rb:0 in `blah'" or # an Array of Arrays that represent a frame: ["/foo.pp", 0] def self.format_backtrace_array(primary_stack, puppetstack = []) primary_stack.flat_map do |frame| frame = format_puppetstack_frame(frame) if frame.is_a?(Array) primary_frame = resolve_stackframe(frame) if primary_frame =~ PUPPET_STACK_INSERTION_FRAME && !puppetstack.empty? [resolve_stackframe(format_puppetstack_frame(puppetstack.shift)), primary_frame] else primary_frame end end end def self.resolve_stackframe(frame) _, path, rest = /^(.*):(\d+.*)$/.match(frame).to_a if path path = begin Pathname(path).realpath rescue path end "#{path}:#{rest}" else frame end end def self.format_puppetstack_frame(file_and_lineno) file_and_lineno.join(':') end # Replace a file, securely. This takes a block, and passes it the file # handle of a file open for writing. Write the replacement content inside # the block and it will safely replace the target file. # # This method will make no changes to the target file until the content is # successfully written and the block returns without raising an error. # # As far as possible the state of the existing file, such as mode, is # preserved. This works hard to avoid loss of any metadata, but will result # in an inode change for the file. # # Arguments: `filename`, `default_mode`, `staging_location` # # The filename is the file we are going to replace. # # The default_mode is the mode to use when the target file doesn't already # exist; if the file is present we copy the existing mode/owner/group values # across. The default_mode can be expressed as an octal integer, a numeric string (ie '0664') # or a symbolic file mode. # # The staging_location is a location to render the temporary file before # moving the file to it's final location. DEFAULT_POSIX_MODE = 0o644 DEFAULT_WINDOWS_MODE = nil def replace_file(file, default_mode, staging_location: nil, validate_callback: nil, &block) raise Puppet::DevError, _("replace_file requires a block") unless block_given? if default_mode unless valid_symbolic_mode?(default_mode) raise Puppet::DevError, _("replace_file default_mode: %{default_mode} is invalid") % { default_mode: default_mode } end mode = symbolic_mode_to_int(normalize_symbolic_mode(default_mode)) elsif Puppet::Util::Platform.windows? mode = DEFAULT_WINDOWS_MODE else mode = DEFAULT_POSIX_MODE end begin file = Puppet::FileSystem.pathname(file) # encoding for Uniquefile is not important here because the caller writes to it as it sees fit if staging_location tempfile = Puppet::FileSystem::Uniquefile.new(Puppet::FileSystem.basename_string(file), staging_location) else tempfile = Puppet::FileSystem::Uniquefile.new(Puppet::FileSystem.basename_string(file), Puppet::FileSystem.dir_string(file)) end effective_mode = unless Puppet::Util::Platform.windows? # Grab the current file mode, and fall back to the defaults. if Puppet::FileSystem.exist?(file) stat = Puppet::FileSystem.lstat(file) tempfile.chown(stat.uid, stat.gid) stat.mode else mode end end # OK, now allow the caller to write the content of the file. yield tempfile if effective_mode # We only care about the bottom four slots, which make the real mode, # and not the rest of the platform stat call fluff and stuff. tempfile.chmod(effective_mode & 0o7777) end # Now, make sure the data (which includes the mode) is safe on disk. tempfile.flush begin tempfile.fsync rescue NotImplementedError # fsync may not be implemented by Ruby on all platforms, but # there is absolutely no recovery path if we detect that. So, we just # ignore the return code. # # However, don't be fooled: that is accepting that we are running in # an unsafe fashion. If you are porting to a new platform don't stub # that out. end tempfile.close if validate_callback validate_callback.call(tempfile.path) end if Puppet::Util::Platform.windows? # Windows ReplaceFile needs a file to exist, so touch handles this unless Puppet::FileSystem.exist?(file) Puppet::FileSystem.touch(file) if mode Puppet::Util::Windows::Security.set_mode(mode, Puppet::FileSystem.path_string(file)) end end # Yes, the arguments are reversed compared to the rename in the rest # of the world. Puppet::Util::Windows::File.replace_file(FileSystem.path_string(file), tempfile.path) else # MRI Ruby checks for this and raises an error, while JRuby removes the directory # and replaces it with a file. This makes the our version of replace_file() consistent if Puppet::FileSystem.exist?(file) && Puppet::FileSystem.directory?(file) raise Errno::EISDIR, _("Is a directory: %{directory}") % { directory: file } end File.rename(tempfile.path, Puppet::FileSystem.path_string(file)) end ensure # in case an error occurred before we renamed the temp file, make sure it # gets deleted if tempfile tempfile.close! end end # Ideally, we would now fsync the directory as well, but Ruby doesn't # have support for that, and it doesn't matter /that/ much... # Return something true, and possibly useful. file end module_function :replace_file # Executes a block of code, wrapped with some special exception handling. Causes the ruby interpreter to # exit if the block throws an exception. # # @api public # @param [String] message a message to log if the block fails # @param [Integer] code the exit code that the ruby interpreter should return if the block fails # @yield def exit_on_fail(message, code = 1) yield # First, we need to check and see if we are catching a SystemExit error. These will be raised # when we daemonize/fork, and they do not necessarily indicate a failure case. rescue SystemExit => err raise err # Now we need to catch *any* other kind of exception, because we may be calling third-party # code (e.g. webrick), and we have no idea what they might throw. rescue Exception => err ## NOTE: when debugging spec failures, these two lines can be very useful # puts err.inspect # puts Puppet::Util.pretty_backtrace(err.backtrace) Puppet.log_exception(err, "#{message}: #{err}") Puppet::Util::Log.force_flushqueue() exit(code) end module_function :exit_on_fail def deterministic_rand(seed, max) deterministic_rand_int(seed, max).to_s end module_function :deterministic_rand def deterministic_rand_int(seed, max) Random.new(seed).rand(max) end module_function :deterministic_rand_int # Executes a block of code, wrapped around Facter.load_external(false) and # Facter.load_external(true) which will cause Facter to not evaluate external facts. def skip_external_facts return yield unless Puppet.runtime[:facter].load_external? begin Puppet.runtime[:facter].load_external(false) yield ensure Puppet.runtime[:facter].load_external(true) end end module_function :skip_external_facts end end require_relative 'util/errors' require_relative 'util/metaid' require_relative 'util/classgen' require_relative 'util/docs' require_relative 'util/execution' require_relative 'util/logging' require_relative 'util/package' require_relative 'util/warnings'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/confine.rb
lib/puppet/confine.rb
# frozen_string_literal: true # The class that handles testing whether our providers # actually work or not. require_relative '../puppet/util' class Puppet::Confine include Puppet::Util @tests = {} class << self attr_accessor :name end def self.inherited(klass) name = klass.to_s.split("::").pop.downcase.to_sym raise "Test #{name} is already defined" if @tests.include?(name) klass.name = name @tests[name] = klass end def self.test(name) unless @tests.include?(name) begin require "puppet/confine/#{name}" rescue LoadError => detail unless detail.to_s =~ /No such file|cannot load such file/i Puppet.warning("Could not load confine test '#{name}': #{detail}") end # Could not find file unless Puppet[:always_retry_plugins] @tests[name] = nil end end end @tests[name] end attr_reader :values # Mark that this confine is used for testing binary existence. attr_accessor :for_binary def for_binary? for_binary end # Used for logging. attr_accessor :label def initialize(values) values = [values] unless values.is_a?(Array) @values = values end # Provide a hook for the message when there's a failure. def message(value) "" end # Collect the results of all of them. def result values.collect { |value| pass?(value) } end # Test whether our confine matches. def valid? values.each do |value| unless pass?(value) Puppet.debug { label + ": " + message(value) } return false end end true ensure reset end # Provide a hook for subclasses. def reset end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/x509/pem_store.rb
lib/puppet/x509/pem_store.rb
# frozen_string_literal: true require_relative '../../puppet/x509' # Methods for managing PEM encoded files. While PEM encoded strings are # always ASCII, the files may contain user specified comments, so they are # UTF-8 encoded. # # @api private module Puppet::X509::PemStore # Load a pem encoded object. # # @param path [String] file path # @return [String, nil] The PEM encoded object or nil if the # path does not exist # @raise [Errno::EACCES] if permission is denied # @api private def load_pem(path) Puppet::FileSystem.read(path, encoding: 'UTF-8') rescue Errno::ENOENT nil end # Save pem encoded content to a file. If the file doesn't exist, it # will be created. Otherwise, the file will be overwritten. In both # cases the contents will be overwritten atomically so other # processes don't see a partially written file. # # @param pem [String] The PEM encoded object to write # @param path [String] The file path to write to # @raise [Errno::EACCES] if permission is denied # @raise [Errno::EPERM] if the operation cannot be completed # @api private def save_pem(pem, path, owner: nil, group: nil, mode: 0o644) Puppet::FileSystem.replace_file(path, mode) do |f| f.set_encoding('UTF-8') f.write(pem.encode('UTF-8')) end if !Puppet::Util::Platform.windows? && Puppet.features.root? && (owner || group) FileUtils.chown(owner, group, path) end end # Delete a pem encoded object, if it exists. # # @param path [String] The file path to delete # @return [Boolean] Returns true if the file was deleted, false otherwise # @raise [Errno::EACCES] if permission is denied # @api private def delete_pem(path) Puppet::FileSystem.unlink(path) true rescue Errno::ENOENT false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/x509/cert_provider.rb
lib/puppet/x509/cert_provider.rb
# frozen_string_literal: true require_relative '../../puppet/x509' # Class for loading and saving cert related objects. By default the provider # loads and saves based on puppet's default settings, such as `Puppet[:localcacert]`. # The providers sets the permissions on files it saves, such as the private key. # All of the `load_*` methods take an optional `required` parameter. If an object # doesn't exist, then by default the provider returns `nil`. However, if the # `required` parameter is true, then an exception will be raised instead. # # @api private class Puppet::X509::CertProvider include Puppet::X509::PemStore # Only allow printing ascii characters, excluding / VALID_CERTNAME = /\A[ -.0-~]+\Z/ CERT_DELIMITERS = /-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----/m CRL_DELIMITERS = /-----BEGIN X509 CRL-----.*?-----END X509 CRL-----/m def initialize(capath: Puppet[:localcacert], crlpath: Puppet[:hostcrl], privatekeydir: Puppet[:privatekeydir], certdir: Puppet[:certdir], requestdir: Puppet[:requestdir], hostprivkey: Puppet.settings.set_by_config?(:hostprivkey) ? Puppet[:hostprivkey] : nil, hostcert: Puppet.settings.set_by_config?(:hostcert) ? Puppet[:hostcert] : nil) @capath = capath @crlpath = crlpath @privatekeydir = privatekeydir @certdir = certdir @requestdir = requestdir @hostprivkey = hostprivkey @hostcert = hostcert end # Save `certs` to the configured `capath`. # # @param certs [Array<OpenSSL::X509::Certificate>] Array of CA certs to save # @raise [Puppet::Error] if the certs cannot be saved # # @api private def save_cacerts(certs) save_pem(certs.map(&:to_pem).join, @capath, **permissions_for_setting(:localcacert)) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to save CA certificates to '%{capath}'") % { capath: @capath }, e) end # Load CA certs from the configured `capath`. # # @param required [Boolean] If true, raise if they are missing # @return (see #load_cacerts_from_pem) # @raise (see #load_cacerts_from_pem) # @raise [Puppet::Error] if the certs cannot be loaded # # @api private def load_cacerts(required: false) pem = load_pem(@capath) if !pem && required raise Puppet::Error, _("The CA certificates are missing from '%{path}'") % { path: @capath } end pem ? load_cacerts_from_pem(pem) : nil rescue SystemCallError => e raise Puppet::Error.new(_("Failed to load CA certificates from '%{capath}'") % { capath: @capath }, e) end # Load PEM encoded CA certificates. # # @param pem [String] PEM encoded certificate(s) # @return [Array<OpenSSL::X509::Certificate>] Array of CA certs # @raise [OpenSSL::X509::CertificateError] The `pem` text does not contain a valid cert # # @api private def load_cacerts_from_pem(pem) # TRANSLATORS 'PEM' is an acronym and shouldn't be translated raise OpenSSL::X509::CertificateError, _("Failed to parse CA certificates as PEM") if pem !~ CERT_DELIMITERS pem.scan(CERT_DELIMITERS).map do |text| OpenSSL::X509::Certificate.new(text) end end # Save `crls` to the configured `crlpath`. # # @param crls [Array<OpenSSL::X509::CRL>] Array of CRLs to save # @raise [Puppet::Error] if the CRLs cannot be saved # # @api private def save_crls(crls) save_pem(crls.map(&:to_pem).join, @crlpath, **permissions_for_setting(:hostcrl)) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to save CRLs to '%{crlpath}'") % { crlpath: @crlpath }, e) end # Load CRLs from the configured `crlpath` path. # # @param required [Boolean] If true, raise if they are missing # @return (see #load_crls_from_pem) # @raise (see #load_crls_from_pem) # @raise [Puppet::Error] if the CRLs cannot be loaded # # @api private def load_crls(required: false) pem = load_pem(@crlpath) if !pem && required raise Puppet::Error, _("The CRL is missing from '%{path}'") % { path: @crlpath } end pem ? load_crls_from_pem(pem) : nil rescue SystemCallError => e raise Puppet::Error.new(_("Failed to load CRLs from '%{crlpath}'") % { crlpath: @crlpath }, e) end # Load PEM encoded CRL(s). # # @param pem [String] PEM encoded CRL(s) # @return [Array<OpenSSL::X509::CRL>] Array of CRLs # @raise [OpenSSL::X509::CRLError] The `pem` text does not contain a valid CRL # # @api private def load_crls_from_pem(pem) # TRANSLATORS 'PEM' is an acronym and shouldn't be translated raise OpenSSL::X509::CRLError, _("Failed to parse CRLs as PEM") if pem !~ CRL_DELIMITERS pem.scan(CRL_DELIMITERS).map do |text| OpenSSL::X509::CRL.new(text) end end # Return the time when the CRL was last updated. # # @return [Time, nil] Time when the CRL was last updated, or nil if we don't # have a CRL # # @api private def crl_last_update stat = Puppet::FileSystem.stat(@crlpath) Time.at(stat.mtime) rescue Errno::ENOENT nil end # Set the CRL last updated time. # # @param time [Time] The last updated time # # @api private def crl_last_update=(time) Puppet::FileSystem.touch(@crlpath, mtime: time) end # Return the time when the CA bundle was last updated. # # @return [Time, nil] Time when the CA bundle was last updated, or nil if we don't # have a CA bundle # # @api private def ca_last_update stat = Puppet::FileSystem.stat(@capath) Time.at(stat.mtime) rescue Errno::ENOENT nil end # Set the CA bundle last updated time. # # @param time [Time] The last updated time # # @api private def ca_last_update=(time) Puppet::FileSystem.touch(@capath, mtime: time) end # Save named private key in the configured `privatekeydir`. For # historical reasons, names are case insensitive. # # @param name [String] The private key identity # @param key [OpenSSL::PKey::RSA] private key # @param password [String, nil] If non-nil, derive an encryption key # from the password, and use that to encrypt the private key. If nil, # save the private key unencrypted. # @raise [Puppet::Error] if the private key cannot be saved # # @api private def save_private_key(name, key, password: nil) pem = if password cipher = OpenSSL::Cipher.new('aes-128-cbc') key.export(cipher, password) else key.to_pem end path = @hostprivkey || to_path(@privatekeydir, name) save_pem(pem, path, **permissions_for_setting(:hostprivkey)) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to save private key for '%{name}'") % { name: name }, e) end # Load a private key from the configured `privatekeydir`. For # historical reasons, names are case-insensitive. # # @param name [String] The private key identity # @param required [Boolean] If true, raise if it is missing # @param password [String, nil] If the private key is encrypted, decrypt # it using the password. If the key is encrypted, but a password is # not specified, then the key cannot be loaded. # @return (see #load_private_key_from_pem) # @raise (see #load_private_key_from_pem) # @raise [Puppet::Error] if the private key cannot be loaded # # @api private def load_private_key(name, required: false, password: nil) path = @hostprivkey || to_path(@privatekeydir, name) pem = load_pem(path) if !pem && required raise Puppet::Error, _("The private key is missing from '%{path}'") % { path: path } end pem ? load_private_key_from_pem(pem, password: password) : nil rescue SystemCallError => e raise Puppet::Error.new(_("Failed to load private key for '%{name}'") % { name: name }, e) end # Load a PEM encoded private key. # # @param pem [String] PEM encoded private key # @param password [String, nil] If the private key is encrypted, decrypt # it using the password. If the key is encrypted, but a password is # not specified, then the key cannot be loaded. # @return [OpenSSL::PKey::RSA, OpenSSL::PKey::EC] The private key # @raise [OpenSSL::PKey::PKeyError] The `pem` text does not contain a valid key # # @api private def load_private_key_from_pem(pem, password: nil) # set a non-nil password to ensure openssl doesn't prompt password ||= '' OpenSSL::PKey.read(pem, password) end # Load the private key password. # # @return [String, nil] The private key password as a binary string or nil # if there is none. # # @api private def load_private_key_password Puppet::FileSystem.read(Puppet[:passfile], :encoding => Encoding::BINARY) rescue Errno::ENOENT nil end # Save a named client cert to the configured `certdir`. # # @param name [String] The client cert identity # @param cert [OpenSSL::X509::Certificate] The cert to save # @raise [Puppet::Error] if the client cert cannot be saved # # @api private def save_client_cert(name, cert) path = @hostcert || to_path(@certdir, name) save_pem(cert.to_pem, path, **permissions_for_setting(:hostcert)) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to save client certificate for '%{name}'") % { name: name }, e) end # Load a named client cert from the configured `certdir`. # # @param name [String] The client cert identity # @param required [Boolean] If true, raise it is missing # @return (see #load_request_from_pem) # @raise (see #load_client_cert_from_pem) # @raise [Puppet::Error] if the client cert cannot be loaded # # @api private def load_client_cert(name, required: false) path = @hostcert || to_path(@certdir, name) pem = load_pem(path) if !pem && required raise Puppet::Error, _("The client certificate is missing from '%{path}'") % { path: path } end pem ? load_client_cert_from_pem(pem) : nil rescue SystemCallError => e raise Puppet::Error.new(_("Failed to load client certificate for '%{name}'") % { name: name }, e) end # Load a PEM encoded certificate. # # @param pem [String] PEM encoded cert # @return [OpenSSL::X509::Certificate] the certificate # @raise [OpenSSL::X509::CertificateError] The `pem` text does not contain a valid cert # # @api private def load_client_cert_from_pem(pem) OpenSSL::X509::Certificate.new(pem) end # Create a certificate signing request (CSR). # # @param name [String] the request identity # @param private_key [OpenSSL::PKey::RSA] private key # @return [Puppet::X509::Request] The request # # @api private def create_request(name, private_key) options = {} if Puppet[:dns_alt_names] && Puppet[:dns_alt_names] != '' options[:dns_alt_names] = Puppet[:dns_alt_names] end csr_attributes = Puppet::SSL::CertificateRequestAttributes.new(Puppet[:csr_attributes]) if csr_attributes.load options[:csr_attributes] = csr_attributes.custom_attributes options[:extension_requests] = csr_attributes.extension_requests end # Adds auto-renew attribute to CSR if the agent supports auto-renewal of # certificates if Puppet[:hostcert_renewal_interval] && Puppet[:hostcert_renewal_interval] > 0 options[:csr_attributes] ||= {} options[:csr_attributes].merge!({ '1.3.6.1.4.1.34380.1.3.2' => 'true' }) end csr = Puppet::SSL::CertificateRequest.new(name) csr.generate(private_key, options) end # Save a certificate signing request (CSR) to the configured `requestdir`. # # @param name [String] the request identity # @param csr [OpenSSL::X509::Request] the request # @raise [Puppet::Error] if the cert request cannot be saved # # @api private def save_request(name, csr) path = to_path(@requestdir, name) save_pem(csr.to_pem, path, **permissions_for_setting(:hostcsr)) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to save certificate request for '%{name}'") % { name: name }, e) end # Load a named certificate signing request (CSR) from the configured `requestdir`. # # @param name [String] The request identity # @return (see #load_request_from_pem) # @raise (see #load_request_from_pem) # @raise [Puppet::Error] if the cert request cannot be saved # # @api private def load_request(name) path = to_path(@requestdir, name) pem = load_pem(path) pem ? load_request_from_pem(pem) : nil rescue SystemCallError => e raise Puppet::Error.new(_("Failed to load certificate request for '%{name}'") % { name: name }, e) end # Delete a named certificate signing request (CSR) from the configured `requestdir`. # # @param name [String] The request identity # @return [Boolean] true if the CSR was deleted # # @api private def delete_request(name) path = to_path(@requestdir, name) delete_pem(path) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to delete certificate request for '%{name}'") % { name: name }, e) end # Load a PEM encoded certificate signing request (CSR). # # @param pem [String] PEM encoded request # @return [OpenSSL::X509::Request] the request # @raise [OpenSSL::X509::RequestError] The `pem` text does not contain a valid request # # @api private def load_request_from_pem(pem) OpenSSL::X509::Request.new(pem) end # Return the path to the cert related object (key, CSR, cert, etc). # # @param base [String] base directory # @param name [String] the name associated with the cert related object def to_path(base, name) raise _("Certname %{name} must not contain unprintable or non-ASCII characters") % { name: name.inspect } unless name =~ VALID_CERTNAME File.join(base, "#{name.downcase}.pem") end private def permissions_for_setting(name) setting = Puppet.settings.setting(name) perm = { mode: setting.mode.to_i(8) } if Puppet.features.root? && !Puppet::Util::Platform.windows? perm[:owner] = setting.owner perm[:group] = setting.group end perm end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/storage.rb
lib/puppet/util/storage.rb
# frozen_string_literal: true require 'yaml' require 'singleton' require_relative '../../puppet/util/yaml' # a class for storing state class Puppet::Util::Storage include Singleton include Puppet::Util def self.state @@state end def initialize self.class.load end # Return a hash that will be stored to disk. It's worth noting # here that we use the object's full path, not just the name/type # combination. At the least, this is useful for those non-isomorphic # types like exec, but it also means that if an object changes locations # in the configuration it will lose its cache. def self.cache(object) if object.is_a?(Symbol) name = object else name = object.to_s end @@state[name] ||= {} end def self.clear @@state.clear end def self.init @@state = {} end init def self.load Puppet.settings.use(:main) unless FileTest.directory?(Puppet[:statedir]) filename = Puppet[:statefile] unless Puppet::FileSystem.exist?(filename) init if @@state.nil? return end unless File.file?(filename) Puppet.warning(_("Checksumfile %{filename} is not a file, ignoring") % { filename: filename }) return end Puppet::Util.benchmark(:debug, "Loaded state in %{seconds} seconds") do @@state = Puppet::Util::Yaml.safe_load_file(filename, [Symbol, Time]) rescue Puppet::Util::Yaml::YamlLoadError => detail Puppet.err _("Checksumfile %{filename} is corrupt (%{detail}); replacing") % { filename: filename, detail: detail } begin File.rename(filename, filename + ".bad") rescue raise Puppet::Error, _("Could not rename corrupt %{filename}; remove manually") % { filename: filename }, detail.backtrace end end unless @@state.is_a?(Hash) Puppet.err _("State got corrupted") init end end def self.stateinspect @@state.inspect end def self.store Puppet.debug "Storing state" Puppet.info _("Creating state file %{file}") % { file: Puppet[:statefile] } unless Puppet::FileSystem.exist?(Puppet[:statefile]) if Puppet[:statettl] == 0 || Puppet[:statettl] == Float::INFINITY Puppet.debug "Not pruning old state cache entries" else Puppet::Util.benchmark(:debug, "Pruned old state cache entries in %{seconds} seconds") do ttl_cutoff = Time.now - Puppet[:statettl] @@state.reject! do |k, _v| @@state[k][:checked] && @@state[k][:checked] < ttl_cutoff end end end Puppet::Util.benchmark(:debug, "Stored state in %{seconds} seconds") do Puppet::Util::Yaml.dump(@@state, Puppet[:statefile]) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/reference.rb
lib/puppet/util/reference.rb
# frozen_string_literal: true require_relative '../../puppet/util/instance_loader' require 'fileutils' # Manage Reference Documentation. class Puppet::Util::Reference include Puppet::Util include Puppet::Util::Docs extend Puppet::Util::InstanceLoader instance_load(:reference, 'puppet/reference') def self.modes %w[text] end def self.newreference(name, options = {}, &block) ref = new(name, **options, &block) instance_hash(:reference)[name.intern] = ref ref end def self.page(*sections) depth = 4 # Use the minimum depth sections.each do |name| section = reference(name) or raise _("Could not find section %{name}") % { name: name } depth = section.depth if section.depth < depth end end def self.references(environment) instance_loader(:reference).loadall(environment) loaded_instances(:reference).sort_by(&:to_s) end attr_accessor :page, :depth, :header, :title, :dynamic attr_writer :doc def doc if defined?(@doc) "#{@name} - #{@doc}" else @title end end def dynamic? dynamic end def initialize(name, title: nil, depth: nil, dynamic: nil, doc: nil, &block) @name = name @title = title @depth = depth @dynamic = dynamic @doc = doc meta_def(:generate, &block) # Now handle the defaults @title ||= _("%{name} Reference") % { name: @name.to_s.capitalize } @page ||= @title.gsub(/\s+/, '') @depth ||= 2 @header ||= "" end # Indent every line in the chunk except those which begin with '..'. def indent(text, tab) text.gsub(/(^|\A)/, tab).gsub(/^ +\.\./, "..") end def option(name, value) ":#{name.to_s.capitalize}: #{value}\n" end def text puts output end def to_markdown(withcontents = true) # First the header text = markdown_header(@title, 1) text << @header text << generate text end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/platform.rb
lib/puppet/util/platform.rb
# frozen_string_literal: true module Puppet module Util module Platform FIPS_STATUS_FILE = "/proc/sys/crypto/fips_enabled" WINDOWS_FIPS_REGISTRY_KEY = 'System\\CurrentControlSet\\Control\\Lsa\\FipsAlgorithmPolicy' def windows? # Ruby only sets File::ALT_SEPARATOR on Windows and the Ruby standard # library uses that to test what platform it's on. In some places we # would use Puppet.features.microsoft_windows?, but this method can be # used to determine the behavior of the underlying system without # requiring features to be initialized and without side effect. !!File::ALT_SEPARATOR end module_function :windows? def solaris? RUBY_PLATFORM.include?('solaris') end module_function :solaris? def default_paths return [] if windows? %w[/usr/sbin /sbin] end module_function :default_paths @fips_enabled = if windows? require 'win32/registry' begin Win32::Registry::HKEY_LOCAL_MACHINE.open(WINDOWS_FIPS_REGISTRY_KEY) do |reg| reg.values.first == 1 end rescue Win32::Registry::Error false end else File.exist?(FIPS_STATUS_FILE) && File.read(FIPS_STATUS_FILE, 1) == '1' end def fips_enabled? @fips_enabled end module_function :fips_enabled? def self.jruby? RUBY_PLATFORM == 'java' end def jruby_fips? @@jruby_fips ||= if RUBY_PLATFORM == 'java' require 'java' begin require 'openssl' false rescue LoadError, NameError true end else false end end module_function :jruby_fips? end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/json_lockfile.rb
lib/puppet/util/json_lockfile.rb
# frozen_string_literal: true require_relative '../../puppet/util/lockfile' # This class provides a simple API for managing a lock file # whose contents are a serialized JSON object. In addition # to querying the basic state (#locked?) of the lock, managing # the lock (#lock, #unlock), the contents can be retrieved at # any time while the lock is held (#lock_data). This can be # used to store structured data (state messages, etc.) about # the lock. # # @see Puppet::Util::Lockfile class Puppet::Util::JsonLockfile < Puppet::Util::Lockfile # Lock the lockfile. You may optionally pass a data object, which will be # retrievable for the duration of time during which the file is locked. # # @param [Hash] lock_data an optional Hash of data to associate with the lock. # This may be used to store pids, descriptive messages, etc. The # data may be retrieved at any time while the lock is held by # calling the #lock_data method. <b>NOTE</b> that the JSON serialization # does NOT support Symbol objects--if you pass them in, they will be # serialized as Strings, so you should plan accordingly. # @return [boolean] true if lock is successfully acquired, false otherwise. def lock(lock_data = nil) return false if locked? super(Puppet::Util::Json.dump(lock_data)) end # Retrieve the (optional) lock data that was specified at the time the file # was locked. # @return [Object] the data object. Remember that the serialization does not # support Symbol objects, so if your data Object originally contained symbols, # they will be converted to Strings. def lock_data return nil unless file_locked? file_contents = super return nil if file_contents.nil? or file_contents.empty? Puppet::Util::Json.load(file_contents) rescue Puppet::Util::Json::ParseError Puppet.warning _("Unable to read lockfile data from %{path}: not in JSON") % { path: @file_path } nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/watcher.rb
lib/puppet/util/watcher.rb
# frozen_string_literal: true module Puppet::Util::Watcher require_relative 'watcher/timer' require_relative 'watcher/change_watcher' require_relative 'watcher/periodic_watcher' module Common def self.file_ctime_change_watcher(filename) Puppet::Util::Watcher::ChangeWatcher.watch(lambda do Puppet::FileSystem.stat(filename).ctime rescue Errno::ENOENT, Errno::ENOTDIR :absent end) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/limits.rb
lib/puppet/util/limits.rb
# frozen_string_literal: true require_relative '../../puppet/util' module Puppet::Util::Limits # @api private def setpriority(priority) return unless priority Process.setpriority(0, Process.pid, priority) rescue Errno::EACCES, NotImplementedError Puppet.warning(_("Failed to set process priority to '%{priority}'") % { priority: priority }) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/autoload.rb
lib/puppet/util/autoload.rb
# frozen_string_literal: true require 'pathname' require_relative '../../puppet/util/rubygems' require_relative '../../puppet/util/warnings' require_relative '../../puppet/pops/adaptable' require_relative '../../puppet/concurrent/synchronized' # An adapter that ties the module_directories cache to the environment where the modules are parsed. This # adapter ensures that the life-cycle of this cache doesn't exceed the life-cycle of the environment. # # @api private class Puppet::Util::ModuleDirectoriesAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :directories def self.create_adapter(env) adapter = super(env) adapter.directories = env.modulepath.flat_map do |dir| Dir.glob(File.join(dir, '*', 'lib')) end adapter end end # Autoload paths, either based on names or all at once. class Puppet::Util::Autoload include Puppet::Concurrent::Synchronized extend Puppet::Concurrent::Synchronized @loaded = {} class << self attr_accessor :loaded def gem_source @gem_source ||= Puppet::Util::RubyGems::Source.new end # Has a given path been loaded? This is used for testing whether a # changed file should be loaded or just ignored. This is only # used in network/client/master, when downloading plugins, to # see if a given plugin is currently loaded and thus should be # reloaded. def loaded?(path) path = cleanpath(path).chomp('.rb') loaded.include?(path) end # Save the fact that a given path has been loaded. This is so # we can load downloaded plugins if they've already been loaded # into memory. # @api private def mark_loaded(name, file) name = cleanpath(name).chomp('.rb') file = File.expand_path(file) $LOADED_FEATURES << file unless $LOADED_FEATURES.include?(file) loaded[name] = [file, File.mtime(file)] end # @api private def changed?(name, env) name = cleanpath(name).chomp('.rb') return true unless loaded.include?(name) file, old_mtime = loaded[name] return true unless file == get_file(name, env) begin old_mtime.to_i != File.mtime(file).to_i rescue Errno::ENOENT true end end # Load a single plugin by name. We use 'load' here so we can reload a # given plugin. def load_file(name, env) file = get_file(name.to_s, env) return false unless file begin mark_loaded(name, file) Kernel.load file true rescue SystemExit, NoMemoryError raise rescue Exception => detail message = _("Could not autoload %{name}: %{detail}") % { name: name, detail: detail } Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end end def loadall(path, env) # Load every instance of everything we can find. files_to_load(path, env).each do |file| name = file.chomp(".rb") load_file(name, env) unless loaded?(name) end end def reload_changed(env) loaded.keys.each do |file| if changed?(file, env) load_file(file, env) end end end # Get the correct file to load for a given path # returns nil if no file is found # @api private def get_file(name, env) name += '.rb' unless name =~ /\.rb$/ path = search_directories(env).find { |dir| Puppet::FileSystem.exist?(File.join(dir, name)) } path and File.join(path, name) end def files_to_load(path, env) search_directories(env).map { |dir| files_in_dir(dir, path) }.flatten.uniq end # @api private def files_in_dir(dir, path) dir = Pathname.new(Puppet::FileSystem.expand_path(dir)) Dir.glob(File.join(dir, path, "*.rb")).collect do |file| Pathname.new(file).relative_path_from(dir).to_s end end # @api private def module_directories(env) raise ArgumentError, "Autoloader requires an environment" unless env Puppet::Util::ModuleDirectoriesAdapter.adapt(env).directories end # @api private def gem_directories gem_source.directories end # @api private def search_directories(env) # This is a little bit of a hack. Basically, the autoloader is being # called indirectly during application bootstrapping when we do things # such as check "features". However, during bootstrapping, we haven't # yet parsed all of the command line parameters nor the config files, # and thus we don't yet know with certainty what the module path is. # This should be irrelevant during bootstrapping, because anything that # we are attempting to load during bootstrapping should be something # that we ship with puppet, and thus the module path is irrelevant. # # In the long term, I think the way that we want to handle this is to # have the autoloader ignore the module path in all cases where it is # not specifically requested (e.g., by a constructor param or # something)... because there are very few cases where we should # actually be loading code from the module path. However, until that # happens, we at least need a way to prevent the autoloader from # attempting to access the module path before it is initialized. For # now we are accomplishing that by calling the # "app_defaults_initialized?" method on the main puppet Settings object. # --cprice 2012-03-16 if Puppet.settings.app_defaults_initialized? gem_directories + module_directories(env) + $LOAD_PATH else gem_directories + $LOAD_PATH end end # Normalize a path. This converts ALT_SEPARATOR to SEPARATOR on Windows # and eliminates unnecessary parts of a path. def cleanpath(path) Pathname.new(path).cleanpath.to_s end end attr_accessor :object, :path def initialize(obj, path) @path = path.to_s raise ArgumentError, _("Autoload paths cannot be fully qualified") if Puppet::Util.absolute_path?(@path) @object = obj end def load(name, env) self.class.load_file(expand(name), env) end # Load all instances from a path of Autoload.search_directories matching the # relative path this Autoloader was initialized with. For example, if we # have created a Puppet::Util::Autoload for Puppet::Type::User with a path of # 'puppet/provider/user', the search_directories path will be searched for # all ruby files matching puppet/provider/user/*.rb and they will then be # loaded from the first directory in the search path providing them. So # earlier entries in the search path may shadow later entries. # # This uses require, rather than load, so that already-loaded files don't get # reloaded unnecessarily. def loadall(env) self.class.loadall(@path, env) end def loaded?(name) self.class.loaded?(expand(name)) end # @api private def changed?(name, env) self.class.changed?(expand(name), env) end def files_to_load(env) self.class.files_to_load(@path, env) end def expand(name) ::File.join(@path, name.to_s) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/diff.rb
lib/puppet/util/diff.rb
# frozen_string_literal: true require 'tempfile' # Provide a diff between two strings. module Puppet::Util::Diff include Puppet::Util::Execution require 'tempfile' def diff(old, new) diff_cmd = Puppet[:diff] return '' unless diff_cmd && diff_cmd != "" command = [diff_cmd] args = Puppet[:diff_args] if args && args != "" args.split(' ').each do |arg| command << arg end end command << old << new Puppet::Util::Execution.execute(command, :failonfail => false, :combine => false) end module_function :diff # return diff string of two input strings # format defaults to unified # context defaults to 3 lines def lcs_diff(data_old, data_new, format = :unified, context_lines = 3) unless Puppet.features.diff? Puppet.warning _("Cannot provide diff without the diff/lcs Ruby library") return "" end data_old = data_old.split(/\n/).map!(&:chomp) data_new = data_new.split(/\n/).map!(&:chomp) output = ''.dup diffs = ::Diff::LCS.diff(data_old, data_new) return output if diffs.empty? oldhunk = hunk = nil file_length_difference = 0 diffs.each do |piece| hunk = ::Diff::LCS::Hunk.new( data_old, data_new, piece, context_lines, file_length_difference ) file_length_difference = hunk.file_length_difference next unless oldhunk # Hunks may overlap, which is why we need to be careful when our # diff includes lines of context. Otherwise, we might print # redundant lines. if (context_lines > 0) and hunk.overlaps?(oldhunk) hunk.unshift(oldhunk) else output << oldhunk.diff(format) end ensure oldhunk = hunk output << "\n" end # Handle the last remaining hunk output << oldhunk.diff(format) << "\n" end def string_file_diff(path, string) tempfile = Tempfile.new("puppet-diffing") tempfile.open tempfile.print string tempfile.close notice "\n" + diff(path, tempfile.path) tempfile.delete end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/monkey_patches.rb
lib/puppet/util/monkey_patches.rb
# frozen_string_literal: true require_relative '../../puppet/util/platform' module Puppet::Util::MonkeyPatches end begin Process.maxgroups = 1024 rescue NotImplementedError # Actually, I just want to ignore it, since various platforms - JRuby, # Windows, and so forth - don't support it, but only because it isn't a # meaningful or implementable concept there. end module RDoc def self.caller(skip = nil) in_gem_wrapper = false Kernel.caller.reject { |call| in_gem_wrapper ||= call =~ /#{Regexp.escape $PROGRAM_NAME}:\d+:in `load'/ } end end class Object # ActiveSupport 2.3.x mixes in a dangerous method # that can cause rspec to fork bomb # and other strange things like that. def daemonize raise NotImplementedError, "Kernel.daemonize is too dangerous, please don't try to use it." end end unless Dir.singleton_methods.include?(:exists?) class Dir def self.exists?(file_name) warn("Dir.exists?('#{file_name}') is deprecated, use Dir.exist? instead") if $VERBOSE Dir.exist?(file_name) end end end unless File.singleton_methods.include?(:exists?) class File def self.exists?(file_name) warn("File.exists?('#{file_name}') is deprecated, use File.exist? instead") if $VERBOSE File.exist?(file_name) end end end require_relative '../../puppet/ssl/openssl_loader' unless Puppet::Util::Platform.jruby_fips? class OpenSSL::SSL::SSLContext if DEFAULT_PARAMS[:options] DEFAULT_PARAMS[:options] |= OpenSSL::SSL::OP_NO_SSLv3 else DEFAULT_PARAMS[:options] = OpenSSL::SSL::OP_NO_SSLv3 end alias __original_initialize initialize private :__original_initialize def initialize(*args) __original_initialize(*args) params = { :options => DEFAULT_PARAMS[:options], :ciphers => DEFAULT_PARAMS[:ciphers], } set_params(params) end end end if Puppet::Util::Platform.windows? class OpenSSL::X509::Store @puppet_certs_loaded = false alias __original_set_default_paths set_default_paths def set_default_paths # This can be removed once openssl integrates with windows # cert store, see https://rt.openssl.org/Ticket/Display.html?id=2158 unless @puppet_certs_loaded @puppet_certs_loaded = true Puppet::Util::Windows::RootCerts.instance.to_a.uniq(&:to_der).each do |x509| add_cert(x509) rescue OpenSSL::X509::StoreError warn "Failed to add #{x509.subject.to_utf8}" end end __original_set_default_paths end end end unless Puppet::Util::Platform.jruby_fips? unless defined?(OpenSSL::X509::V_ERR_HOSTNAME_MISMATCH) module OpenSSL::X509 OpenSSL::X509::V_ERR_HOSTNAME_MISMATCH = 0x3E end end # jruby-openssl doesn't support this unless OpenSSL::X509::Name.instance_methods.include?(:to_utf8) class OpenSSL::X509::Name def to_utf8 # https://github.com/ruby/ruby/blob/v2_5_5/ext/openssl/ossl_x509name.c#L317 str = to_s(OpenSSL::X509::Name::RFC2253) str.force_encoding(Encoding::UTF_8) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/execution_stub.rb
lib/puppet/util/execution_stub.rb
# frozen_string_literal: true module Puppet::Util class ExecutionStub class << self # Set a stub block that Puppet::Util::Execution.execute() should invoke instead # of actually executing commands on the target machine. Intended # for spec testing. # # The arguments passed to the block are |command, options|, where # command is an array of strings and options is an options hash. def set(&block) @value = block end # Uninstall any execution stub, so that calls to # Puppet::Util::Execution.execute() behave normally again. def reset @value = nil end # Retrieve the current execution stub, or nil if there is no stub. def current_value @value end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/plist.rb
lib/puppet/util/plist.rb
# frozen_string_literal: true require 'cfpropertylist' if Puppet.features.cfpropertylist? require_relative '../../puppet/util/execution' module Puppet::Util::Plist class FormatError < RuntimeError; end # So I don't have to prepend every method name with 'self.' Most of the # methods are going to be Provider methods (as opposed to methods of the # INSTANCE of the provider). class << self # Defines the magic number for binary plists # # @api private def binary_plist_magic_number "bplist00" end # Defines a default doctype string that should be at the top of most plist # files. Useful if we need to modify an invalid doctype string in memory. # In version 10.9 and lower of OS X the plist at # /System/Library/LaunchDaemons/org.ntp.ntpd.plist had an invalid doctype # string. This corrects for that. def plist_xml_doctype '<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' end # Read a plist file, whether its format is XML or in Apple's "binary1" # format, using the CFPropertyList gem. def read_plist_file(file_path) # We can't really read the file until we know the source encoding in # Ruby 1.9.x, so we use the magic number to detect it. # NOTE: We used IO.read originally to be Ruby 1.8.x compatible. if read_file_with_offset(file_path, binary_plist_magic_number.length) == binary_plist_magic_number plist_obj = new_cfpropertylist(:file => file_path) return convert_cfpropertylist_to_native_types(plist_obj) else plist_data = open_file_with_args(file_path, "r:UTF-8") plist = parse_plist(plist_data, file_path) return plist if plist Puppet.debug "Plist #{file_path} ill-formatted, converting with plutil" begin plist = Puppet::Util::Execution.execute(['/usr/bin/plutil', '-convert', 'xml1', '-o', '-', file_path], { :failonfail => true, :combine => true }) return parse_plist(plist) rescue Puppet::ExecutionFailure => detail message = _("Cannot read file %{file_path}; Puppet is skipping it.") % { file_path: file_path } message += '\n' + _("Details: %{detail}") % { detail: detail } Puppet.warning(message) end end nil end # Read plist text using the CFPropertyList gem. def parse_plist(plist_data, file_path = '') bad_xml_doctype = %r{^.*<!DOCTYPE plist PUBLIC -//Apple Computer.*$} # Depending on where parse_plist is called from, plist_data can be either XML or binary. # If we get XML, make sure ruby knows it's UTF-8 so we avoid invalid byte sequence errors. if plist_data.include?('encoding="UTF-8"') && plist_data.encoding != Encoding::UTF_8 plist_data.force_encoding(Encoding::UTF_8) end begin if plist_data =~ bad_xml_doctype plist_data.gsub!(bad_xml_doctype, plist_xml_doctype) Puppet.debug("Had to fix plist with incorrect DOCTYPE declaration: #{file_path}") end rescue ArgumentError => e Puppet.debug "Failed with #{e.class} on #{file_path}: #{e.inspect}" return nil end begin plist_obj = new_cfpropertylist(:data => plist_data) # CFPropertyList library will raise NoMethodError for invalid data rescue CFFormatError, NoMethodError => e Puppet.debug "Failed with #{e.class} on #{file_path}: #{e.inspect}" return nil end convert_cfpropertylist_to_native_types(plist_obj) end # Helper method to assist in reading a file. It's its own method for # stubbing purposes # # @api private # # @param args [String] Extra file operation mode information to use # (defaults to read-only mode 'r') # This is the standard mechanism Ruby uses in the IO class, and therefore # encoding may be explicitly like fmode : encoding or fmode : "BOM|UTF-*" # for example, a:ASCII or w+:UTF-8 def open_file_with_args(file, args) File.open(file, args).read end # Helper method to assist in generating a new CFPropertyList Plist. It's # its own method for stubbing purposes # # @api private def new_cfpropertylist(plist_opts) CFPropertyList::List.new(plist_opts) end # Helper method to assist in converting a native CFPropertyList object to a # native Ruby object (hash). It's its own method for stubbing purposes # # @api private def convert_cfpropertylist_to_native_types(plist_obj) CFPropertyList.native_types(plist_obj.value) end # Helper method to convert a string into a CFProperty::Blob, which is # needed to properly handle binary strings # # @api private def string_to_blob(str) CFPropertyList::Blob.new(str) end # Helper method to assist in reading a file with an offset value. It's its # own method for stubbing purposes # # @api private def read_file_with_offset(file_path, offset) IO.read(file_path, offset) end def to_format(format) case format.to_sym when :xml CFPropertyList::List::FORMAT_XML when :binary CFPropertyList::List::FORMAT_BINARY when :plain CFPropertyList::List::FORMAT_PLAIN else raise FormatError, "Unknown plist format #{format}" end end # This method will write a plist file using a specified format (or XML # by default) def write_plist_file(plist, file_path, format = :xml) plist_to_save = CFPropertyList::List.new plist_to_save.value = CFPropertyList.guess(plist) plist_to_save.save(file_path, to_format(format), :formatted => true) rescue IOError => e Puppet.err(_("Unable to write the file %{file_path}. %{error}") % { file_path: file_path, error: e.inspect }) end def dump_plist(plist_data, format = :xml) plist_to_save = CFPropertyList::List.new plist_to_save.value = CFPropertyList.guess(plist_data) plist_to_save.to_str(to_format(format), :formatted => true) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/libuser.rb
lib/puppet/util/libuser.rb
# frozen_string_literal: true module Puppet::Util::Libuser def self.getconf File.expand_path('libuser.conf', __dir__) end def self.getenv newenv = {} newenv['LIBUSER_CONF'] = getconf newenv end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/http_proxy.rb
lib/puppet/util/http_proxy.rb
# frozen_string_literal: true require_relative '../../puppet/http' # for backwards compatibility Puppet::Util::HttpProxy = Puppet::HTTP::Proxy
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/errors.rb
lib/puppet/util/errors.rb
# frozen_string_literal: true # Some helper methods for throwing and populating errors. # # @api public module Puppet::Util::Errors # Throw a Puppet::DevError with the specified message. Used for unknown or # internal application failures. # # @param msg [String] message used in raised error # @raise [Puppet::DevError] always raised with the supplied message def devfail(msg) self.fail(Puppet::DevError, msg) end # Add line and file info to the supplied exception if info is available from # this object, is appropriately populated and the supplied exception supports # it. When other is supplied, the backtrace will be copied to the error # object and the 'original' will be dropped from the error. # # @param error [Exception] exception that is populated with info # @param other [Exception] original exception, source of backtrace info # @return [Exception] error parameter def adderrorcontext(error, other = nil) error.line ||= line if error.respond_to?(:line=) and respond_to?(:line) and line error.file ||= file if error.respond_to?(:file=) and respond_to?(:file) and file error.original ||= other if error.respond_to?(:original=) error.set_backtrace(other.backtrace) if other and other.respond_to?(:backtrace) # It is not meaningful to keep the wrapped exception since its backtrace has already # been adopted by the error. (The instance variable is private for good reasons). error.instance_variable_set(:@original, nil) error end # Return a human-readable string of this object's file, line, and pos attributes, # if set. # # @param file [String] the file path for the error (nil or "", for not known) # @param line [String] the line number for the error (nil or "", for not known) # @param column [String] the column number for the error (nil or "", for not known) # @return [String] description of file, line, and column # def self.error_location(file, line = nil, column = nil) file = nil if file.is_a?(String) && file.empty? line = nil if line.is_a?(String) && line.empty? column = nil if column.is_a?(String) && column.empty? if file and line and column _("(file: %{file}, line: %{line}, column: %{column})") % { file: file, line: line, column: column } elsif file and line _("(file: %{file}, line: %{line})") % { file: file, line: line } elsif line and column _("(line: %{line}, column: %{column})") % { line: line, column: column } elsif line _("(line: %{line})") % { line: line } elsif file _("(file: %{file})") % { file: file } else '' end end # Return a human-readable string of this object's file, line, and pos attributes, # with a proceeding space in the output # if set. # # @param file [String] the file path for the error (nil or "", for not known) # @param line [String] the line number for the error (nil or "", for not known) # @param column [String] the column number for the error (nil or "", for not known) # @return [String] description of file, line, and column # def self.error_location_with_space(file, line = nil, column = nil) error_location_str = error_location(file, line, column) if error_location_str.empty? '' else ' ' + error_location_str end end # Return a human-readable string of this object's file and line # where unknown entries are listed as 'unknown' # # @param file [String] the file path for the error (nil or "", for not known) # @param line [String] the line number for the error (nil or "", for not known) # @return [String] description of file, and line def self.error_location_with_unknowns(file, line) file = nil if file.is_a?(String) && file.empty? line = nil if line.is_a?(String) && line.empty? file ||= _('unknown') line ||= _('unknown') error_location(file, line) end # Return a human-readable string of this object's file and line attributes, # if set. # # @return [String] description of file and line with a leading space def error_context Puppet::Util::Errors.error_location_with_space(file, line) end # Wrap a call in such a way that we always throw the right exception and keep # as much context as possible. # # @param options [Hash<Symbol,Object>] options used to create error # @option options [Class] :type error type to raise, defaults to # Puppet::DevError # @option options [String] :message message to use in error, default mentions # the name of this class # @raise [Puppet::Error] re-raised with extra context if the block raises it # @raise [Error] of type options[:type], when the block raises other # exceptions def exceptwrap(options = {}) options[:type] ||= Puppet::DevError begin return yield rescue Puppet::Error => detail raise adderrorcontext(detail) rescue => detail message = options[:message] || _("%{klass} failed with error %{error_type}: %{detail}") % { klass: self.class, error_type: detail.class, detail: detail } error = options[:type].new(message) # We can't use self.fail here because it always expects strings, # not exceptions. raise adderrorcontext(error, detail) end retval end # Throw an error, defaulting to a Puppet::Error. # # @overload fail(message, ..) # Throw a Puppet::Error with a message concatenated from the given # arguments. # @param [String] message error message(s) # @overload fail(error_klass, message, ..) # Throw an exception of type error_klass with a message concatenated from # the given arguments. # @param [Class] type of error # @param [String] message error message(s) # @overload fail(error_klass, message, ..) # Throw an exception of type error_klass with a message concatenated from # the given arguments. # @param [Class] type of error # @param [String] message error message(s) # @param [Exception] original exception, source of backtrace info def fail(*args) if args[0].is_a?(Class) type = args.shift else type = Puppet::Error end other = args.count > 1 ? args.pop : nil error = adderrorcontext(type.new(args.join(" ")), other) raise error end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/lockfile.rb
lib/puppet/util/lockfile.rb
# frozen_string_literal: true # This class provides a simple API for managing a lock file # whose contents are an (optional) String. In addition # to querying the basic state (#locked?) of the lock, managing # the lock (#lock, #unlock), the contents can be retrieved at # any time while the lock is held (#lock_data). This can be # used to store pids, messages, etc. # # @see Puppet::Util::JsonLockfile class Puppet::Util::Lockfile attr_reader :file_path def initialize(file_path) @file_path = file_path end # Lock the lockfile. You may optionally pass a data object, which will be # retrievable for the duration of time during which the file is locked. # # @param [String] lock_data an optional String data object to associate # with the lock. This may be used to store pids, descriptive messages, # etc. The data may be retrieved at any time while the lock is held by # calling the #lock_data method. # @return [boolean] true if lock is successfully acquired, false otherwise. def lock(lock_data = nil) Puppet::FileSystem.exclusive_create(@file_path, nil) do |fd| fd.print(lock_data) end true rescue Errno::EEXIST false end def unlock if locked? Puppet::FileSystem.unlink(@file_path) true else false end end def locked? # delegate logic to a more explicit private method file_locked? end # Retrieve the (optional) lock data that was specified at the time the file # was locked. # @return [String] the data object. def lock_data File.read(@file_path) if file_locked? end # Private, internal utility method for encapsulating the logic about # whether or not the file is locked. This method can be called # by other methods in this class without as much risk of accidentally # being overridden by child classes. # @return [boolean] true if the file is locked, false if it is not. def file_locked? Puppet::FileSystem.exist? @file_path end private :file_locked? end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/profiler.rb
lib/puppet/util/profiler.rb
# frozen_string_literal: true require 'benchmark' # A simple profiling callback system. # # @api public module Puppet::Util::Profiler require_relative 'profiler/wall_clock' require_relative 'profiler/object_counts' require_relative 'profiler/around_profiler' @profiler = Puppet::Util::Profiler::AroundProfiler.new # Reset the profiling system to the original state # # @api private def self.clear @profiler.clear end # Retrieve the current list of profilers # # @api private def self.current @profiler.current end # @param profiler [#profile] A profiler for the current thread # @api private def self.add_profiler(profiler) @profiler.add_profiler(profiler) end # @param profiler [#profile] A profiler to remove from the current thread # @api private def self.remove_profiler(profiler) @profiler.remove_profiler(profiler) end # Profile a block of code and log the time it took to execute. # # This outputs logs entries to the Puppet masters logging destination # providing the time it took, a message describing the profiled code # and a leaf location marking where the profile method was called # in the profiled hierarchy. # # @param message [String] A description of the profiled event # @param metric_id [Array] A list of strings making up the ID of a metric to profile # @param block [Block] The segment of code to profile # @api public def self.profile(message, metric_id, &block) @profiler.profile(message, metric_id, &block) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/at_fork.rb
lib/puppet/util/at_fork.rb
# frozen_string_literal: true require_relative '../../puppet' # A module for building AtFork handlers. These handlers are objects providing # pre/post fork callbacks modeled after those registered by the `pthread_atfork` # function. # Currently there are two AtFork handler implementations: # - a noop implementation used on all platforms except Solaris (and possibly # even there as a fallback) # - a Solaris implementation which ensures the forked process runs in a different # contract than the parent process. This is necessary for agent runs started by # the puppet agent service to be able to restart that service without being # killed in the process as a consequence of running in the same contract as the # service. module Puppet::Util::AtFork @handler_class = loop do # rubocop:disable Lint/UnreachableLoop if Puppet::Util::Platform.solaris? begin require_relative 'at_fork/solaris' # using break to return a value from the loop block break Puppet::Util::AtFork::Solaris rescue LoadError => detail Puppet.log_exception(detail, _('Failed to load Solaris implementation of the Puppet::Util::AtFork handler. Child process contract management will be unavailable, which means that agent runs executed by the puppet agent service will be killed when they attempt to restart the service.')) # fall through to use the no-op implementation end end require_relative 'at_fork/noop' # using break to return a value from the loop block break Puppet::Util::AtFork::Noop end def self.get_handler @handler_class.new end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/filetype.rb
lib/puppet/util/filetype.rb
# frozen_string_literal: true # Basic classes for reading, writing, and emptying files. Not much # to see here. require_relative '../../puppet/util/selinux' require 'tempfile' require 'fileutils' class Puppet::Util::FileType attr_accessor :loaded, :path, :synced class FileReadError < Puppet::Error; end include Puppet::Util::SELinux class << self attr_accessor :name include Puppet::Util::ClassGen end # Create a new filetype. def self.newfiletype(name, &block) @filetypes ||= {} klass = genclass( name, :block => block, :prefix => "FileType", :hash => @filetypes ) # Rename the read and write methods, so that we're sure they # maintain the stats. klass.class_eval do # Rename the read method define_method(:real_read, instance_method(:read)) define_method(:read) do val = real_read @loaded = Time.now if val val.gsub(/# HEADER.*\n/, '') else "" end rescue Puppet::Error raise rescue => detail message = _("%{klass} could not read %{path}: %{detail}") % { klass: self.class, path: @path, detail: detail } Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end # And then the write method define_method(:real_write, instance_method(:write)) define_method(:write) do |text| val = real_write(text) @synced = Time.now val rescue Puppet::Error raise rescue => detail message = _("%{klass} could not write %{path}: %{detail}") % { klass: self.class, path: @path, detail: detail } Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end end end def self.filetype(type) @filetypes[type] end # Pick or create a filebucket to use. def bucket @bucket ||= Puppet::Type.type(:filebucket).mkdefaultbucket.bucket end def initialize(path, default_mode = nil) raise ArgumentError, _("Path is nil") if path.nil? @path = path @default_mode = default_mode end # Arguments that will be passed to the execute method. Will set the uid # to the target user if the target user and the current user are not # the same def cronargs uid = Puppet::Util.uid(@path) if uid && uid == Puppet::Util::SUIDManager.uid { :failonfail => true, :combine => true } else { :failonfail => true, :combine => true, :uid => @path } end end # Operate on plain files. newfiletype(:flat) do # Back the file up before replacing it. def backup bucket.backup(@path) if Puppet::FileSystem.exist?(@path) end # Read the file. def read if Puppet::FileSystem.exist?(@path) # this code path is used by many callers so the original default is # being explicitly preserved Puppet::FileSystem.read(@path, :encoding => Encoding.default_external) else nil end end # Remove the file. def remove Puppet::FileSystem.unlink(@path) if Puppet::FileSystem.exist?(@path) end # Overwrite the file. def write(text) # this file is managed by the OS and should be using system encoding tf = Tempfile.new("puppet", :encoding => Encoding.default_external) tf.print text; tf.flush File.chmod(@default_mode, tf.path) if @default_mode FileUtils.cp(tf.path, @path) tf.close # If SELinux is present, we need to ensure the file has its expected context set_selinux_default_context(@path) end end # Operate on plain files. newfiletype(:ram) do @@tabs = {} def self.clear @@tabs.clear end def initialize(path, default_mode = nil) # default_mode is meaningless for this filetype, # supported only for compatibility with :flat super @@tabs[@path] ||= "" end # Read the file. def read Puppet.info _("Reading %{path} from RAM") % { path: @path } @@tabs[@path] end # Remove the file. def remove Puppet.info _("Removing %{path} from RAM") % { path: @path } @@tabs[@path] = "" end # Overwrite the file. def write(text) Puppet.info _("Writing %{path} to RAM") % { path: @path } @@tabs[@path] = text end end # Handle Linux-style cron tabs. # # TODO: We can possibly eliminate the "-u <username>" option in cmdbase # by just running crontab under <username>'s uid (like we do for suntab # and aixtab). It may be worth investigating this alternative # implementation in the future. This way, we can refactor all three of # our cron file types into a common crontab file type. newfiletype(:crontab) do def initialize(user) self.path = user end def path=(user) begin @uid = Puppet::Util.uid(user) rescue Puppet::Error => detail raise FileReadError, _("Could not retrieve user %{user}: %{detail}") % { user: user, detail: detail }, detail.backtrace end # XXX We have to have the user name, not the uid, because some # systems *cough*linux*cough* require it that way @path = user end # Read a specific @path's cron tab. def read unless Puppet::Util.uid(@path) Puppet.debug _("The %{path} user does not exist. Treating their crontab file as empty in case Puppet creates them in the middle of the run.") % { path: @path } return "" end Puppet::Util::Execution.execute("#{cmdbase} -l", failonfail: true, combine: true) rescue => detail case detail.to_s when /no crontab for/ "" when /are not allowed to/ Puppet.debug _("The %{path} user is not authorized to use cron. Their crontab file is treated as empty in case Puppet authorizes them in the middle of the run (by, for example, modifying the cron.deny or cron.allow files).") % { path: @path } "" else raise FileReadError, _("Could not read crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace end end # Remove a specific @path's cron tab. def remove cmd = "#{cmdbase} -r" if %w[Darwin FreeBSD DragonFly].include?(Puppet.runtime[:facter].value('os.name')) cmd = "/bin/echo yes | #{cmd}" end Puppet::Util::Execution.execute(cmd, failonfail: true, combine: true) end # Overwrite a specific @path's cron tab; must be passed the @path name # and the text with which to create the cron tab. # # TODO: We should refactor this at some point to make it identical to the # :aixtab and :suntab's write methods so that, at the very least, the pipe # is not created and the crontab command's errors are not swallowed. def write(text) unless Puppet::Util.uid(@path) raise Puppet::Error, _("Cannot write the %{path} user's crontab: The user does not exist") % { path: @path } end # this file is managed by the OS and should be using system encoding IO.popen("#{cmdbase()} -", "w", :encoding => Encoding.default_external) { |p| p.print text } end private # Only add the -u flag when the @path is different. Fedora apparently # does not think I should be allowed to set the @path to my own user name def cmdbase if @uid == Puppet::Util::SUIDManager.uid || Puppet.runtime[:facter].value('os.name') == "HP-UX" "crontab" else "crontab -u #{@path}" end end end # SunOS has completely different cron commands; this class implements # its versions. newfiletype(:suntab) do # Read a specific @path's cron tab. def read unless Puppet::Util.uid(@path) Puppet.debug _("The %{path} user does not exist. Treating their crontab file as empty in case Puppet creates them in the middle of the run.") % { path: @path } return "" end Puppet::Util::Execution.execute(%w[crontab -l], cronargs) rescue => detail case detail.to_s when /can't open your crontab/ "" when /you are not authorized to use cron/ Puppet.debug _("The %{path} user is not authorized to use cron. Their crontab file is treated as empty in case Puppet authorizes them in the middle of the run (by, for example, modifying the cron.deny or cron.allow files).") % { path: @path } "" else raise FileReadError, _("Could not read crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace end end # Remove a specific @path's cron tab. def remove Puppet::Util::Execution.execute(%w[crontab -r], cronargs) rescue => detail raise FileReadError, _("Could not remove crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace end # Overwrite a specific @path's cron tab; must be passed the @path name # and the text with which to create the cron tab. def write(text) # this file is managed by the OS and should be using system encoding output_file = Tempfile.new("puppet_suntab", :encoding => Encoding.default_external) begin output_file.print text output_file.close # We have to chown the stupid file to the user. File.chown(Puppet::Util.uid(@path), nil, output_file.path) Puppet::Util::Execution.execute(["crontab", output_file.path], cronargs) rescue => detail raise FileReadError, _("Could not write crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace ensure output_file.close output_file.unlink end end end # Support for AIX crontab with output different than suntab's crontab command. newfiletype(:aixtab) do # Read a specific @path's cron tab. def read unless Puppet::Util.uid(@path) Puppet.debug _("The %{path} user does not exist. Treating their crontab file as empty in case Puppet creates them in the middle of the run.") % { path: @path } return "" end Puppet::Util::Execution.execute(%w[crontab -l], cronargs) rescue => detail case detail.to_s when /open.*in.*directory/ "" when /not.*authorized.*cron/ Puppet.debug _("The %{path} user is not authorized to use cron. Their crontab file is treated as empty in case Puppet authorizes them in the middle of the run (by, for example, modifying the cron.deny or cron.allow files).") % { path: @path } "" else raise FileReadError, _("Could not read crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace end end # Remove a specific @path's cron tab. def remove Puppet::Util::Execution.execute(%w[crontab -r], cronargs) rescue => detail raise FileReadError, _("Could not remove crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace end # Overwrite a specific @path's cron tab; must be passed the @path name # and the text with which to create the cron tab. def write(text) # this file is managed by the OS and should be using system encoding output_file = Tempfile.new("puppet_aixtab", :encoding => Encoding.default_external) begin output_file.print text output_file.close # We have to chown the stupid file to the user. File.chown(Puppet::Util.uid(@path), nil, output_file.path) Puppet::Util::Execution.execute(["crontab", output_file.path], cronargs) rescue => detail raise FileReadError, _("Could not write crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace ensure output_file.close output_file.unlink end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/instance_loader.rb
lib/puppet/util/instance_loader.rb
# frozen_string_literal: true require_relative '../../puppet/util/autoload' require_relative '../../puppet/util' require_relative '../../puppet/concurrent/lock' # A module that can easily autoload things for us. Uses an instance # of Puppet::Util::Autoload module Puppet::Util::InstanceLoader include Puppet::Util # Are we instance-loading this type? def instance_loading?(type) defined?(@autoloaders) and @autoloaders.include?(type.intern) end # Define a new type of autoloading. def instance_load(type, path) @autoloaders ||= {} @instances ||= {} type = type.intern @instances[type] = {} @autoloaders[type] = Puppet::Util::Autoload.new(self, path) @instance_loader_lock = Puppet::Concurrent::Lock.new # Now define our new simple methods unless respond_to?(type) meta_def(type) do |name| loaded_instance(type, name) end end end # Return a list of the names of all instances def loaded_instances(type) @instances[type].keys end # Return the instance hash for our type. def instance_hash(type) @instances[type.intern] end # Return the Autoload object for a given type. def instance_loader(type) @autoloaders[type.intern] end # Retrieve an already-loaded instance, or attempt to load our instance. def loaded_instance(type, name) @instance_loader_lock.synchronize do name = name.intern instances = instance_hash(type) return nil unless instances unless instances.include? name if instance_loader(type).load(name, Puppet.lookup(:current_environment)) unless instances.include? name Puppet.warning(_("Loaded %{type} file for %{name} but %{type} was not defined") % { type: type, name: name }) return nil end else return nil end end instances[name] end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package.rb
lib/puppet/util/package.rb
# frozen_string_literal: true module Puppet::Util::Package def versioncmp(version_a, version_b, ignore_trailing_zeroes = false) vre = /[-.]|\d+|[^-.\d]+/ if ignore_trailing_zeroes version_a = normalize(version_a) version_b = normalize(version_b) end ax = version_a.scan(vre) bx = version_b.scan(vre) while ax.length > 0 && bx.length > 0 a = ax.shift b = bx.shift next if a == b return -1 if a == '-' return 1 if b == '-' return -1 if a == '.' return 1 if b == '.' if a =~ /^\d+$/ && b =~ /^\d+$/ return a.to_s.upcase <=> b.to_s.upcase if a =~ /^0/ || b =~ /^0/ return a.to_i <=> b.to_i end return a.upcase <=> b.upcase end version_a <=> version_b end module_function :versioncmp def self.normalize(version) version = version.split('-') version.first.sub!(/([.0]+)$/, '') version.join('-') end private_class_method :normalize end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/rdoc.rb
lib/puppet/util/rdoc.rb
# frozen_string_literal: true require_relative '../../puppet/util' module Puppet::Util::RDoc module_function # launch a rdoc documentation process # with the files/dir passed in +files+ def rdoc(outputdir, files, charset = nil) # then rdoc require 'rdoc/rdoc' require 'rdoc/options' # load our parser require_relative 'rdoc/parser' r = RDoc::RDoc.new # specify our own format & where to output options = ["--fmt", "puppet", "--quiet", "--exclude", "/modules/[^/]*/spec/.*$", "--exclude", "/modules/[^/]*/files/.*$", "--exclude", "/modules/[^/]*/tests/.*$", "--exclude", "/modules/[^/]*/templates/.*$", "--op", outputdir] options << "--force-update" options += ["--charset", charset] if charset options += files # launch the documentation process r.document(options) end # launch an output to console manifest doc def manifestdoc(files) raise _("RDOC SUPPORT FOR MANIFEST HAS BEEN REMOVED - See PUP-3638") end # Outputs to the console the documentation # of a manifest def output(file, ast) raise _("RDOC SUPPORT FOR MANIFEST HAS BEEN REMOVED - See PUP-3638") end def output_astnode_doc(ast) raise _("RDOC SUPPORT FOR MANIFEST HAS BEEN REMOVED - See PUP-3638") end def output_resource_doc(code) raise _("RDOC SUPPORT FOR MANIFEST HAS BEEN REMOVED - See PUP-3638") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/log.rb
lib/puppet/util/log.rb
# frozen_string_literal: true require_relative '../../puppet/util/tagging' require_relative '../../puppet/util/classgen' require_relative '../../puppet/util/psych_support' require_relative '../../puppet/network/format_support' # Pass feedback to the user. Log levels are modeled after syslog's, and it is # expected that that will be the most common log destination. Supports # multiple destinations, one of which is a remote server. class Puppet::Util::Log include Puppet::Util extend Puppet::Util::ClassGen include Puppet::Util::PsychSupport include Puppet::Util::Tagging include Puppet::Network::FormatSupport @levels = [:debug, :info, :notice, :warning, :err, :alert, :emerg, :crit] @loglevel = 2 @desttypes = {} # Create a new destination type. def self.newdesttype(name, options = {}, &block) dest = genclass( name, :parent => Puppet::Util::Log::Destination, :prefix => "Dest", :block => block, :hash => @desttypes, :attributes => options ) dest.match(dest.name) dest end require_relative 'log/destination' require_relative 'log/destinations' @destinations = {} @queued = [] class << self include Puppet::Util include Puppet::Util::ClassGen attr_reader :desttypes end # Reset log to basics. Basically just flushes and closes files and # undefs other objects. def Log.close(destination) if @destinations.include?(destination) @destinations[destination].flush if @destinations[destination].respond_to?(:flush) @destinations[destination].close if @destinations[destination].respond_to?(:close) @destinations.delete(destination) end end def self.close_all @destinations.keys.each { |dest| close(dest) } # TRANSLATORS "Log.close_all" is a method name and should not be translated raise Puppet::DevError, _("Log.close_all failed to close %{destinations}") % { destinations: @destinations.keys.inspect } unless @destinations.empty? end # Flush any log destinations that support such operations. def Log.flush @destinations.each { |_type, dest| dest.flush if dest.respond_to?(:flush) } end def Log.autoflush=(v) @destinations.each do |_type, dest| dest.autoflush = v if dest.respond_to?(:autoflush=) end end # Create a new log message. The primary role of this method is to # avoid creating log messages below the loglevel. def Log.create(hash) raise Puppet::DevError, _("Logs require a level") unless hash.include?(:level) raise Puppet::DevError, _("Invalid log level %{level}") % { level: hash[:level] } unless @levels.index(hash[:level]) @levels.index(hash[:level]) >= @loglevel ? Puppet::Util::Log.new(hash) : nil end def Log.destinations @destinations end # Yield each valid level in turn def Log.eachlevel @levels.each { |level| yield level } end # Return the current log level. def Log.level @levels[@loglevel] end # Set the current log level. def Log.level=(level) level = level.intern unless level.is_a?(Symbol) # loglevel is a 0-based index loglevel = @levels.index(level) raise Puppet::DevError, _("Invalid loglevel %{level}") % { level: level } unless loglevel return if @loglevel == loglevel # loglevel changed @loglevel = loglevel # Enable or disable Facter debugging Puppet.runtime[:facter].debugging(level == :debug) end def Log.levels @levels.dup end # Create a new log destination. def Log.newdestination(dest) # Each destination can only occur once. if @destinations.find { |_name, obj| obj.name == dest } return end _, type = @desttypes.find do |_name, klass| klass.match?(dest) end if type.respond_to?(:suitable?) and !type.suitable?(dest) return end raise Puppet::DevError, _("Unknown destination type %{dest}") % { dest: dest } unless type begin if type.instance_method(:initialize).arity == 1 @destinations[dest] = type.new(dest) else @destinations[dest] = type.new end flushqueue @destinations[dest] rescue => detail Puppet.log_exception(detail) # If this was our only destination, then add the console back in. if destinations.empty? && dest.intern != :console newdestination(:console) end # Re-raise (end exit Puppet) because we could not set up logging correctly. raise detail end end def Log.with_destination(destination, &block) if @destinations.include?(destination) yield else newdestination(destination) begin yield ensure close(destination) end end end def Log.coerce_string(str) return Puppet::Util::CharacterEncoding.convert_to_utf_8(str) if str.valid_encoding? # We only select the last 10 callers in the stack to avoid being spammy message = _("Received a Log attribute with invalid encoding:%{log_message}") % { log_message: Puppet::Util::CharacterEncoding.convert_to_utf_8(str.dump) } message += '\n' + _("Backtrace:\n%{backtrace}") % { backtrace: caller(1, 10).join("\n") } message end private_class_method :coerce_string # Route the actual message. FIXME There are lots of things this method # should do, like caching and a bit more. It's worth noting that there's # a potential for a loop here, if the machine somehow gets the destination set as # itself. def Log.newmessage(msg) return if @levels.index(msg.level) < @loglevel msg.message = coerce_string(msg.message) msg.source = coerce_string(msg.source) queuemessage(msg) if @destinations.length == 0 @destinations.each do |_name, dest| dest.handle(msg) end end def Log.queuemessage(msg) @queued.push(msg) end def Log.flushqueue return unless @destinations.size >= 1 @queued.each do |msg| Log.newmessage(msg) end @queued.clear end # Flush the logging queue. If there are no destinations available, # adds in a console logger before flushing the queue. # This is mainly intended to be used as a last-resort attempt # to ensure that logging messages are not thrown away before # the program is about to exit--most likely in a horrific # error scenario. # @return nil def Log.force_flushqueue if @destinations.empty? and !@queued.empty? newdestination(:console) end flushqueue end def Log.sendlevel?(level) @levels.index(level) >= @loglevel end # Reopen all of our logs. def Log.reopen Puppet.notice _("Reopening log files") types = @destinations.keys @destinations.each { |_type, dest| dest.close if dest.respond_to?(:close) } @destinations.clear # We need to make sure we always end up with some kind of destination begin types.each { |type| Log.newdestination(type) } rescue => detail if @destinations.empty? Log.setup_default Puppet.err detail.to_s end end end def self.setup_default Log.newdestination( if Puppet.features.syslog? :syslog else Puppet.features.eventlog? ? :eventlog : Puppet[:puppetdlog] end ) end # Is the passed level a valid log level? def self.validlevel?(level) @levels.include?(level) end def self.from_data_hash(data) obj = allocate obj.initialize_from_hash(data) obj end # Log output using scope and level # # @param [Puppet::Parser::Scope] scope # @param [Symbol] level log level # @param [Array<Object>] vals the values to log (will be converted to string and joined with space) # def self.log_func(scope, level, vals) # NOTE: 3x, does this: vals.join(" ") # New implementation uses the evaluator to get proper formatting per type vals = vals.map { |v| Puppet::Pops::Evaluator::EvaluatorImpl.new.string(v, scope) } # Bypass Puppet.<level> call since it picks up source from "self" which is not applicable in the 4x # Function API. # TODO: When a function can obtain the file, line, pos of the call merge those in (3x supports # options :file, :line. (These were never output when calling the 3x logging functions since # 3x scope does not know about the calling location at that detailed level, nor do they # appear in a report to stdout/error when included). Now, the output simply uses scope (like 3x) # as this is good enough, but does not reflect the true call-stack, but is a rough estimate # of where the logging call originates from). # Puppet::Util::Log.create({ :level => level, :source => scope, :message => vals.join(" ") }) nil end attr_accessor :time, :remote, :file, :line, :pos, :issue_code, :environment, :node, :backtrace attr_reader :level, :message, :source def initialize(args) self.level = args[:level] self.message = args[:message] self.source = args[:source] || "Puppet" @time = Time.now tags = args[:tags] if tags tags.each { |t| tag(t) } end # Don't add these unless defined (preserve 3.x API as much as possible) [:file, :line, :pos, :issue_code, :environment, :node, :backtrace].each do |attr| value = args[attr] next unless value send(attr.to_s + '=', value) end Log.newmessage(self) end def initialize_from_hash(data) @level = data['level'].intern @message = data['message'] @source = data['source'] @tags = Puppet::Util::TagSet.new(data['tags']) @time = data['time'] if @time.is_a? String @time = Time.parse(@time) end # Don't add these unless defined (preserve 3.x API as much as possible) %w[file line pos issue_code environment node backtrace].each do |name| value = data[name] next unless value send(name + '=', value) end end def to_hash to_data_hash end def to_data_hash { 'level' => @level.to_s, 'message' => to_s, 'source' => @source, 'tags' => @tags.to_a, 'time' => @time.iso8601(9), 'file' => @file, 'line' => @line, } end def to_structured_hash hash = { 'level' => @level, 'message' => @message, 'source' => @source, 'tags' => @tags.to_a, 'time' => @time.iso8601(9), } %w[file line pos issue_code environment node backtrace].each do |name| attr_name = "@#{name}" hash[name] = instance_variable_get(attr_name) if instance_variable_defined?(attr_name) end hash end def message=(msg) # TRANSLATORS 'Puppet::Util::Log' refers to a Puppet source code class raise ArgumentError, _("Puppet::Util::Log requires a message") unless msg @message = msg.to_s end def level=(level) # TRANSLATORS 'Puppet::Util::Log' refers to a Puppet source code class raise ArgumentError, _("Puppet::Util::Log requires a log level") unless level # TRANSLATORS 'Puppet::Util::Log' refers to a Puppet source code class raise ArgumentError, _("Puppet::Util::Log requires a symbol or string") unless level.respond_to? "to_sym" @level = level.to_sym raise ArgumentError, _("Invalid log level %{level}") % { level: @level } unless self.class.validlevel?(@level) # Tag myself with my log level tag(level) end # If they pass a source in to us, we make sure it is a string, and # we retrieve any tags we can. def source=(source) if defined?(Puppet::Type) && source.is_a?(Puppet::Type) @source = source.path merge_tags_from(source) self.file = source.file self.line = source.line else @source = source.to_s end end def to_report "#{time} #{source} (#{level}): #{self}" end def to_s msg = message # Issue based messages do not have details in the message. It # must be appended here unless issue_code.nil? msg = _("Could not parse for environment %{environment}: %{msg}") % { environment: environment, msg: msg } unless environment.nil? msg += Puppet::Util::Errors.error_location_with_space(file, line, pos) msg = _("%{msg} on node %{node}") % { msg: msg, node: node } unless node.nil? if @backtrace.is_a?(Array) msg += "\n" msg += @backtrace.join("\n") end end msg end end # This is for backward compatibility from when we changed the constant to # Puppet::Util::Log because the reports include the constant name. It was # considered for removal but left in due to risk of breakage (PUP-7502). Puppet::Log = Puppet::Util::Log
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false