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
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/compiler_spec.rb
spec/unit/parser/compiler_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' class CompilerTestResource attr_accessor :builtin, :virtual, :evaluated, :type, :title def initialize(type, title) @type = type @title = title end def [](attr) return nil if (attr == :stage || attr == :alias) :main end def ref "#{type.to_s.capitalize}[#{title}]" end def evaluated? @evaluated end def builtin_type? @builtin end def virtual? @virtual end def class? false end def stage? false end def evaluate end def file "/fake/file/goes/here" end def line "42" end def resource_type self.class end end describe Puppet::Parser::Compiler do include PuppetSpec::Files include Matchers::Resource def resource(type, title) Puppet::Parser::Resource.new(type, title, :scope => @scope) end let(:environment) { Puppet::Node::Environment.create(:testing, []) } before :each do # Push me faster, I wanna go back in time! (Specifically, freeze time # across the test since we have a bunch of version == timestamp code # hidden away in the implementation and we keep losing the race.) # --daniel 2011-04-21 now = Time.now allow(Time).to receive(:now).and_return(now) @node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}), :environment => environment) @known_resource_types = environment.known_resource_types @compiler = Puppet::Parser::Compiler.new(@node) @scope = Puppet::Parser::Scope.new(@compiler, :source => double('source')) @scope_resource = Puppet::Parser::Resource.new(:file, "/my/file", :scope => @scope) @scope.resource = @scope_resource end it "should fail intelligently when a class-level compile fails" do expect(Puppet::Parser::Compiler).to receive(:new).and_raise(ArgumentError) expect { Puppet::Parser::Compiler.compile(@node) }.to raise_error(Puppet::Error) end it "should use the node's environment as its environment" do expect(@compiler.environment).to equal(@node.environment) end it "fails if the node's environment has validation errors" do conflicted_environment = Puppet::Node::Environment.create(:testing, [], '/some/environment.conf/manifest.pp') allow(conflicted_environment).to receive(:validation_errors).and_return(['bad environment']) @node.environment = conflicted_environment expect { Puppet::Parser::Compiler.compile(@node) }.to raise_error(Puppet::Error, /Compilation has been halted because.*bad environment/) end it "should be able to return a class list containing all added classes" do @compiler.add_class "" @compiler.add_class "one" @compiler.add_class "two" expect(@compiler.classlist.sort).to eq(%w{one two}.sort) end describe "when initializing" do it 'should not create the settings class more than once' do logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do Puppet[:code] = 'undef' @compiler.compile @compiler = Puppet::Parser::Compiler.new(@node) Puppet[:code] = 'undef' @compiler.compile end warnings = logs.select { |log| log.level == :warning }.map { |log| log.message } expect(warnings).not_to include(/Class 'settings' is already defined/) end it "should set its node attribute" do expect(@compiler.node).to equal(@node) end it "the set of ast_nodes should be empty" do expect(@compiler.environment.known_resource_types.nodes?).to be_falsey end it "should copy the known_resource_types version to the catalog" do expect(@compiler.catalog.version).to eq(@known_resource_types.version) end it "should copy any node classes into the class list" do node = Puppet::Node.new("mynode") node.classes = %w{foo bar} compiler = Puppet::Parser::Compiler.new(node) expect(compiler.classlist).to match_array(['foo', 'bar']) end it "should transform node class hashes into a class list" do node = Puppet::Node.new("mynode") node.classes = {'foo'=>{'one'=>'p1'}, 'bar'=>{'two'=>'p2'}} compiler = Puppet::Parser::Compiler.new(node) expect(compiler.classlist).to match_array(['foo', 'bar']) end it "should return a catalog with the specified code_id" do node = Puppet::Node.new("mynode") code_id = 'b59e5df0578ef411f773ee6c33d8073c50e7b8fe' compiler = Puppet::Parser::Compiler.new(node, :code_id => code_id) expect(compiler.catalog.code_id).to eq(code_id) end it "should add a 'main' stage to the catalog" do expect(@compiler.catalog.resource(:stage, :main)).to be_instance_of(Puppet::Parser::Resource) end end describe "sanitize_node" do it "should delete trusted from parameters" do node = Puppet::Node.new("mynode") node.parameters['trusted'] = { :a => 42 } node.parameters['preserve_me'] = 'other stuff' compiler = Puppet::Parser::Compiler.new(node) sanitized = compiler.node expect(sanitized.parameters['trusted']).to eq(nil) expect(sanitized.parameters['preserve_me']).to eq('other stuff') end it "should not report trusted_data if trusted is false" do node = Puppet::Node.new("mynode") node.parameters['trusted'] = false compiler = Puppet::Parser::Compiler.new(node) sanitized = compiler.node expect(sanitized.trusted_data).to_not eq(false) end it "should not report trusted_data if trusted is not a hash" do node = Puppet::Node.new("mynode") node.parameters['trusted'] = 'not a hash' compiler = Puppet::Parser::Compiler.new(node) sanitized = compiler.node expect(sanitized.trusted_data).to_not eq('not a hash') end it "should not report trusted_data if trusted hash doesn't include known keys" do node = Puppet::Node.new("mynode") node.parameters['trusted'] = { :a => 42 } compiler = Puppet::Parser::Compiler.new(node) sanitized = compiler.node expect(sanitized.trusted_data).to_not eq({ :a => 42 }) end it "should prefer trusted_data in the node above other plausible sources" do node = Puppet::Node.new("mynode") node.trusted_data = { 'authenticated' => true, 'certname' => 'the real deal', 'extensions' => 'things' } node.parameters['trusted'] = { 'authenticated' => true, 'certname' => 'not me', 'extensions' => 'things' } compiler = Puppet::Parser::Compiler.new(node) sanitized = compiler.node expect(sanitized.trusted_data).to eq({ 'authenticated' => true, 'certname' => 'the real deal', 'extensions' => 'things' }) end end describe "when managing scopes" do it "should create a top scope" do expect(@compiler.topscope).to be_instance_of(Puppet::Parser::Scope) end it "should be able to create new scopes" do expect(@compiler.newscope(@compiler.topscope)).to be_instance_of(Puppet::Parser::Scope) end it "should set the parent scope of the new scope to be the passed-in parent" do scope = double('scope') newscope = @compiler.newscope(scope) expect(newscope.parent).to equal(scope) end it "should set the parent scope of the new scope to its topscope if the parent passed in is nil" do newscope = @compiler.newscope(nil) expect(newscope.parent).to equal(@compiler.topscope) end end describe "when compiling" do it "should set node parameters as variables in the top scope" do params = {"a" => "b", "c" => "d"} allow(@node).to receive(:parameters).and_return(params) @compiler.compile expect(@compiler.topscope['a']).to eq("b") expect(@compiler.topscope['c']).to eq("d") end it "should set node parameters that are of Symbol type as String variables in the top scope" do params = {"a" => :b} allow(@node).to receive(:parameters).and_return(params) @compiler.compile expect(@compiler.topscope['a']).to eq("b") end it "should set the node's environment as a string variable in top scope" do @node.merge({'wat' => 'this is how the sausage is made'}) @compiler.compile expect(@compiler.topscope['environment']).to eq("testing") expect(@compiler.topscope['wat']).to eq('this is how the sausage is made') end it "sets the environment based on node.environment instead of the parameters" do @node.parameters['environment'] = "Not actually #{@node.environment.name}" @compiler.compile expect(@compiler.topscope['environment']).to eq('testing') end it "should set the client and server versions on the catalog" do params = {"clientversion" => "2", "serverversion" => "3"} allow(@node).to receive(:parameters).and_return(params) @compiler.compile expect(@compiler.catalog.client_version).to eq("2") expect(@compiler.catalog.server_version).to eq("3") end it "should evaluate the main class if it exists" do main_class = @known_resource_types.add Puppet::Resource::Type.new(:hostclass, "") @compiler.topscope.source = main_class expect(main_class).to receive(:evaluate_code).with(be_a(Puppet::Parser::Resource)) @compiler.compile end it "should create a new, empty 'main' if no main class exists" do @compiler.compile expect(@known_resource_types.find_hostclass("")).to be_instance_of(Puppet::Resource::Type) end it "should add an edge between the main stage and main class" do @compiler.compile expect(stage = @compiler.catalog.resource(:stage, "main")).to be_instance_of(Puppet::Parser::Resource) expect(klass = @compiler.catalog.resource(:class, "")).to be_instance_of(Puppet::Parser::Resource) expect(@compiler.catalog.edge?(stage, klass)).to be_truthy end it "should evaluate all added collections" do colls = [] # And when the collections fail to evaluate. colls << double("coll1-false") colls << double("coll2-false") colls.each { |c| expect(c).to receive(:evaluate).and_return(false) } @compiler.add_collection(colls[0]) @compiler.add_collection(colls[1]) allow(@compiler).to receive(:fail_on_unevaluated) @compiler.compile end it "should ignore builtin resources" do resource = resource(:file, "testing") @compiler.add_resource(@scope, resource) expect(resource).not_to receive(:evaluate) @compiler.compile end it "should evaluate unevaluated resources" do resource = CompilerTestResource.new(:file, "testing") @compiler.add_resource(@scope, resource) # We have to now mark the resource as evaluated expect(resource).to receive(:evaluate) { resource.evaluated = true } @compiler.compile end it "should not evaluate already-evaluated resources" do resource = resource(:file, "testing") allow(resource).to receive(:evaluated?).and_return(true) @compiler.add_resource(@scope, resource) expect(resource).not_to receive(:evaluate) @compiler.compile end it "should evaluate unevaluated resources created by evaluating other resources" do resource = CompilerTestResource.new(:file, "testing") @compiler.add_resource(@scope, resource) resource2 = CompilerTestResource.new(:file, "other") # We have to now mark the resource as evaluated expect(resource).to receive(:evaluate) { resource.evaluated = true; @compiler.add_resource(@scope, resource2) } expect(resource2).to receive(:evaluate) { resource2.evaluated = true } @compiler.compile end describe "when finishing" do before do @compiler.send(:evaluate_main) @catalog = @compiler.catalog end def add_resource(name, parent = nil) resource = Puppet::Parser::Resource.new "file", name, :scope => @scope @compiler.add_resource(@scope, resource) @catalog.add_edge(parent, resource) if parent resource end it "should call finish() on all resources" do # Add a resource that does respond to :finish resource = Puppet::Parser::Resource.new "file", "finish", :scope => @scope expect(resource).to receive(:finish) @compiler.add_resource(@scope, resource) # And one that does not dnf_resource = double("dnf", :ref => "File[dnf]", :type => "file", :resource_type => nil, :[] => nil, :class? => nil, :stage? => nil) @compiler.add_resource(@scope, dnf_resource) @compiler.send(:finish) end it "should call finish() in add_resource order" do resource1 = add_resource("finish1") expect(resource1).to receive(:finish).ordered resource2 = add_resource("finish2") expect(resource2).to receive(:finish).ordered @compiler.send(:finish) end it "should add each container's metaparams to its contained resources" do main = @catalog.resource(:class, :main) main[:noop] = true resource1 = add_resource("meh", main) @compiler.send(:finish) expect(resource1[:noop]).to be_truthy end it "should add metaparams recursively" do main = @catalog.resource(:class, :main) main[:noop] = true resource1 = add_resource("meh", main) resource2 = add_resource("foo", resource1) @compiler.send(:finish) expect(resource2[:noop]).to be_truthy end it "should prefer metaparams from immediate parents" do main = @catalog.resource(:class, :main) main[:noop] = true resource1 = add_resource("meh", main) resource2 = add_resource("foo", resource1) resource1[:noop] = false @compiler.send(:finish) expect(resource2[:noop]).to be_falsey end it "should merge tags downward" do main = @catalog.resource(:class, :main) main.tag("one") resource1 = add_resource("meh", main) resource1.tag "two" resource2 = add_resource("foo", resource1) @compiler.send(:finish) expect(resource2.tags).to be_include("one") expect(resource2.tags).to be_include("two") end it "should work if only middle resources have metaparams set" do main = @catalog.resource(:class, :main) resource1 = add_resource("meh", main) resource1[:noop] = true resource2 = add_resource("foo", resource1) @compiler.send(:finish) expect(resource2[:noop]).to be_truthy end end it "should return added resources in add order" do resource1 = resource(:file, "yay") @compiler.add_resource(@scope, resource1) resource2 = resource(:file, "youpi") @compiler.add_resource(@scope, resource2) expect(@compiler.resources).to eq([resource1, resource2]) end it "should add resources that do not conflict with existing resources" do resource = resource(:file, "yay") @compiler.add_resource(@scope, resource) expect(@compiler.catalog).to be_vertex(resource) end it "should fail to add resources that conflict with existing resources" do path = make_absolute("/foo") file1 = resource(:file, path) file2 = resource(:file, path) @compiler.add_resource(@scope, file1) expect { @compiler.add_resource(@scope, file2) }.to raise_error(Puppet::Resource::Catalog::DuplicateResourceError) end it "should add an edge from the scope resource to the added resource" do resource = resource(:file, "yay") @compiler.add_resource(@scope, resource) expect(@compiler.catalog).to be_edge(@scope.resource, resource) end it "should not add non-class resources that don't specify a stage to the 'main' stage" do main = @compiler.catalog.resource(:stage, :main) resource = resource(:file, "foo") @compiler.add_resource(@scope, resource) expect(@compiler.catalog).not_to be_edge(main, resource) end it "should not add any parent-edges to stages" do stage = resource(:stage, "other") @compiler.add_resource(@scope, stage) @scope.resource = resource(:class, "foo") expect(@compiler.catalog.edge?(@scope.resource, stage)).to be_falsey end it "should not attempt to add stages to other stages" do other_stage = resource(:stage, "other") second_stage = resource(:stage, "second") @compiler.add_resource(@scope, other_stage) @compiler.add_resource(@scope, second_stage) second_stage[:stage] = "other" expect(@compiler.catalog.edge?(other_stage, second_stage)).to be_falsey end it "should have a method for looking up resources" do resource = resource(:yay, "foo") @compiler.add_resource(@scope, resource) expect(@compiler.findresource("Yay[foo]")).to equal(resource) end it "should be able to look resources up by type and title" do resource = resource(:yay, "foo") @compiler.add_resource(@scope, resource) expect(@compiler.findresource("Yay", "foo")).to equal(resource) end it "should not evaluate virtual defined resources" do resource = resource(:file, "testing") resource.virtual = true @compiler.add_resource(@scope, resource) expect(resource).not_to receive(:evaluate) @compiler.compile end end describe "when evaluating collections" do it "should evaluate each collection" do 2.times { |i| coll = double('coll%s' % i) @compiler.add_collection(coll) # This is the hard part -- we have to emulate the fact that # collections delete themselves if they are done evaluating. expect(coll).to receive(:evaluate) do @compiler.delete_collection(coll) end } @compiler.compile end it "should not fail when there are unevaluated resource collections that do not refer to specific resources" do coll = double('coll', :evaluate => false) expect(coll).to receive(:unresolved_resources).and_return(nil) @compiler.add_collection(coll) expect { @compiler.compile }.not_to raise_error end it "should fail when there are unevaluated resource collections that refer to a specific resource" do coll = double('coll', :evaluate => false) expect(coll).to receive(:unresolved_resources).and_return(:something) @compiler.add_collection(coll) expect { @compiler.compile }.to raise_error(Puppet::ParseError, 'Failed to realize virtual resources something') end it "should fail when there are unevaluated resource collections that refer to multiple specific resources" do coll = double('coll', :evaluate => false) expect(coll).to receive(:unresolved_resources).and_return([:one, :two]) @compiler.add_collection(coll) expect { @compiler.compile }.to raise_error(Puppet::ParseError, 'Failed to realize virtual resources one, two') end end describe "when evaluating relationships" do it "should evaluate each relationship with its catalog" do dep = double('dep') expect(dep).to receive(:evaluate).with(@compiler.catalog) @compiler.add_relationship dep @compiler.evaluate_relationships end end describe "when told to evaluate missing classes" do it "should fail if there's no source listed for the scope" do scope = double('scope', :source => nil) expect { @compiler.evaluate_classes(%w{one two}, scope) }.to raise_error(Puppet::DevError) end it "should raise an error if a class is not found" do expect(@scope.environment.known_resource_types).to receive(:find_hostclass).with("notfound").and_return(nil) expect{ @compiler.evaluate_classes(%w{notfound}, @scope) }.to raise_error(Puppet::Error, /Could not find class/) end it "should raise an error when it can't find class" do klasses = {'foo'=>nil} @node.classes = klasses expect{ @compiler.compile }.to raise_error(Puppet::Error, /Could not find class foo for testnode/) end end describe "when evaluating found classes" do before do Puppet.settings[:data_binding_terminus] = "none" @class = @known_resource_types.add Puppet::Resource::Type.new(:hostclass, "myclass") @resource = double('resource', :ref => "Class[myclass]", :type => "file") end around do |example| Puppet.override( :environments => Puppet::Environments::Static.new(environment), :description => "Static loader for specs" ) do example.run end end it "should evaluate each class" do allow(@compiler.catalog).to receive(:tag) expect(@class).to receive(:ensure_in_catalog).with(@scope) allow(@scope).to receive(:class_scope).with(@class) @compiler.evaluate_classes(%w{myclass}, @scope) end describe "and the classes are specified as a hash with parameters" do before do @node.classes = {} @ast_obj = Puppet::Parser::AST::Leaf.new(:value => 'foo') end # Define the given class with default parameters def define_class(name, parameters) @node.classes[name] = parameters klass = Puppet::Resource::Type.new(:hostclass, name, :arguments => {'p1' => @ast_obj, 'p2' => @ast_obj}) @compiler.environment.known_resource_types.add klass end def compile @catalog = @compiler.compile end it "should record which classes are evaluated" do classes = {'foo'=>{}, 'bar::foo'=>{}, 'bar'=>{}} classes.each { |c, params| define_class(c, params) } compile() classes.each { |name, p| expect(@catalog.classes).to include(name) } end it "should provide default values for parameters that have no values specified" do define_class('foo', {}) compile() expect(@catalog.resource(:class, 'foo')['p1']).to eq("foo") end it "should use any provided values" do define_class('foo', {'p1' => 'real_value'}) compile() expect(@catalog.resource(:class, 'foo')['p1']).to eq("real_value") end it "should support providing some but not all values" do define_class('foo', {'p1' => 'real_value'}) compile() expect(@catalog.resource(:class, 'Foo')['p1']).to eq("real_value") expect(@catalog.resource(:class, 'Foo')['p2']).to eq("foo") end it "should ensure each node class is in catalog and has appropriate tags" do klasses = ['bar::foo'] @node.classes = klasses ast_obj = Puppet::Parser::AST::Leaf.new(:value => 'foo') klasses.each do |name| klass = Puppet::Resource::Type.new(:hostclass, name, :arguments => {'p1' => ast_obj, 'p2' => ast_obj}) @compiler.environment.known_resource_types.add klass end catalog = @compiler.compile r2 = catalog.resources.detect {|r| r.title == 'Bar::Foo' } expect(r2.tags).to eq(Puppet::Util::TagSet.new(['bar::foo', 'class', 'bar', 'foo'])) end end it "should fail if required parameters are missing" do klass = {'foo'=>{'a'=>'one'}} @node.classes = klass klass = Puppet::Resource::Type.new(:hostclass, 'foo', :arguments => {'a' => nil, 'b' => nil}) @compiler.environment.known_resource_types.add klass expect { @compiler.compile }.to raise_error(Puppet::PreformattedError, /Class\[Foo\]: expects a value for parameter 'b'/) end it "should fail if invalid parameters are passed" do klass = {'foo'=>{'3'=>'one'}} @node.classes = klass klass = Puppet::Resource::Type.new(:hostclass, 'foo', :arguments => {}) @compiler.environment.known_resource_types.add klass expect { @compiler.compile }.to raise_error(Puppet::PreformattedError, /Class\[Foo\]: has no parameter named '3'/) end it "should ensure class is in catalog without params" do @node.classes = {'foo'=>nil} foo = Puppet::Resource::Type.new(:hostclass, 'foo') @compiler.environment.known_resource_types.add foo catalog = @compiler.compile expect(catalog.classes).to include 'foo' end it "should not evaluate the resources created for found classes unless asked" do allow(@compiler.catalog).to receive(:tag) expect(@resource).not_to receive(:evaluate) expect(@class).to receive(:ensure_in_catalog).and_return(@resource) allow(@scope).to receive(:class_scope).with(@class) @compiler.evaluate_classes(%w{myclass}, @scope) end it "should immediately evaluate the resources created for found classes when asked" do allow(@compiler.catalog).to receive(:tag) expect(@resource).to receive(:evaluate) expect(@class).to receive(:ensure_in_catalog).and_return(@resource) allow(@scope).to receive(:class_scope).with(@class) @compiler.evaluate_classes(%w{myclass}, @scope, false) end it "should skip classes that have already been evaluated" do allow(@compiler.catalog).to receive(:tag) allow(@scope).to receive(:class_scope).with(@class).and_return(@scope) expect(@compiler).not_to receive(:add_resource) expect(@resource).not_to receive(:evaluate) expect(Puppet::Parser::Resource).not_to receive(:new) @compiler.evaluate_classes(%w{myclass}, @scope, false) end it "should skip classes previously evaluated with different capitalization" do allow(@compiler.catalog).to receive(:tag) allow(@scope.environment.known_resource_types).to receive(:find_hostclass).with("MyClass").and_return(@class) allow(@scope).to receive(:class_scope).with(@class).and_return(@scope) expect(@compiler).not_to receive(:add_resource) expect(@resource).not_to receive(:evaluate) expect(Puppet::Parser::Resource).not_to receive(:new) @compiler.evaluate_classes(%w{MyClass}, @scope, false) end end describe "when evaluating AST nodes with no AST nodes present" do it "should do nothing" do allow(@compiler.environment.known_resource_types).to receive(:nodes).and_return(false) expect(Puppet::Parser::Resource).not_to receive(:new) @compiler.send(:evaluate_ast_node) end end describe "when evaluating AST nodes with AST nodes present" do before do allow(@compiler.environment.known_resource_types).to receive(:nodes?).and_return(true) # Set some names for our test allow(@node).to receive(:names).and_return(%w{a b c}) allow(@compiler.environment.known_resource_types).to receive(:node).with("a").and_return(nil) allow(@compiler.environment.known_resource_types).to receive(:node).with("b").and_return(nil) allow(@compiler.environment.known_resource_types).to receive(:node).with("c").and_return(nil) # It should check this last, of course. allow(@compiler.environment.known_resource_types).to receive(:node).with("default").and_return(nil) end it "should fail if the named node cannot be found" do expect { @compiler.send(:evaluate_ast_node) }.to raise_error(Puppet::ParseError) end it "should evaluate the first node class matching the node name" do node_class = double('node', :name => "c", :evaluate_code => nil) allow(@compiler.environment.known_resource_types).to receive(:node).with("c").and_return(node_class) node_resource = double('node resource', :ref => "Node[c]", :evaluate => nil, :type => "node") expect(node_class).to receive(:ensure_in_catalog).and_return(node_resource) @compiler.compile end it "should match the default node if no matching node can be found" do node_class = double('node', :name => "default", :evaluate_code => nil) allow(@compiler.environment.known_resource_types).to receive(:node).with("default").and_return(node_class) node_resource = double('node resource', :ref => "Node[default]", :evaluate => nil, :type => "node") expect(node_class).to receive(:ensure_in_catalog).and_return(node_resource) @compiler.compile end it "should evaluate the node resource immediately rather than using lazy evaluation" do node_class = double('node', :name => "c") allow(@compiler.environment.known_resource_types).to receive(:node).with("c").and_return(node_class) node_resource = double('node resource', :ref => "Node[c]", :type => "node") expect(node_class).to receive(:ensure_in_catalog).and_return(node_resource) expect(node_resource).to receive(:evaluate) @compiler.send(:evaluate_ast_node) end end describe 'when using meta parameters to form relationships' do include PuppetSpec::Compiler [:before, :subscribe, :notify, :require].each do | meta_p | it "an entry consisting of nested empty arrays is flattened for parameter #{meta_p}" do expect { node = Puppet::Node.new('someone') manifest = <<-"MANIFEST" notify{hello_kitty: message => meow, #{meta_p} => [[],[]]} notify{hello_kitty2: message => meow, #{meta_p} => [[],[[]],[]]} MANIFEST catalog = compile_to_catalog(manifest, node) catalog.to_ral }.not_to raise_error end end end describe "when evaluating node classes" do include PuppetSpec::Compiler describe "when provided classes in array format" do let(:node) { Puppet::Node.new('someone', :classes => ['something']) } describe "when the class exists" do it "should succeed if the class is already included" do manifest = <<-MANIFEST class something {} include something MANIFEST catalog = compile_to_catalog(manifest, node) expect(catalog.resource('Class', 'Something')).not_to be_nil end it "should evaluate the class without parameters if it's not already included" do manifest = "class something {}" catalog = compile_to_catalog(manifest, node) expect(catalog.resource('Class', 'Something')).not_to be_nil end it "raises if the class name is the same as the node definition" do name = node.name node.classes = [name] expect { compile_to_catalog(<<-MANIFEST, node) class #{name} {} node #{name} { include #{name} } MANIFEST }.to raise_error(Puppet::Error, /Class '#{name}' is already defined \(line: 1\); cannot be redefined as a node /) end it "evaluates the class if the node definition uses a regexp" do name = node.name node.classes = [name] catalog = compile_to_catalog(<<-MANIFEST, node) class #{name} {} node /#{name}/ { include #{name} } MANIFEST expect(@logs).to be_empty expect(catalog.resource('Class', node.name.capitalize)).to_not be_nil end end it "should fail if the class doesn't exist" do expect { compile_to_catalog('', node) }.to raise_error(Puppet::Error, /Could not find class something/) end end describe "when provided classes in hash format" do describe "for classes without parameters" do let(:node) { Puppet::Node.new('someone', :classes => {'something' => {}}) } describe "when the class exists" do it "should succeed if the class is already included" do manifest = <<-MANIFEST class something {} include something MANIFEST catalog = compile_to_catalog(manifest, node) expect(catalog.resource('Class', 'Something')).not_to be_nil end it "should evaluate the class if it's not already included" do manifest = <<-MANIFEST class something {} MANIFEST catalog = compile_to_catalog(manifest, node) expect(catalog.resource('Class', 'Something')).not_to be_nil end end it "should fail if the class doesn't exist" do expect { compile_to_catalog('', node) }.to raise_error(Puppet::Error, /Could not find class something/) end end describe "for classes with parameters" do
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/resource/param_spec.rb
spec/unit/parser/resource/param_spec.rb
require 'spec_helper' describe Puppet::Parser::Resource::Param do it "has readers for all of the attributes" do param = Puppet::Parser::Resource::Param.new(:name => 'myparam', :value => 'foo', :file => 'foo.pp', :line => 42) expect(param.name).to eq(:myparam) expect(param.value).to eq('foo') expect(param.file).to eq('foo.pp') expect(param.line).to eq(42) end context "parameter validation" do it "throws an error when instantiated without a name" do expect { Puppet::Parser::Resource::Param.new(:value => 'foo') }.to raise_error(Puppet::Error, /'name' is a required option/) end it "does not require a value" do param = Puppet::Parser::Resource::Param.new(:name => 'myparam') expect(param.value).to be_nil end it "includes file/line context in errors" do expect { Puppet::Parser::Resource::Param.new(:file => 'foo.pp', :line => 42) }.to raise_error(Puppet::Error, /\(file: foo.pp, line: 42\)/) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/file_spec.rb
spec/unit/parser/functions/file_spec.rb
require 'spec_helper' require 'puppet_spec/files' describe "the 'file' function" do include PuppetSpec::Files let :node do Puppet::Node.new('localhost') end let :compiler do Puppet::Parser::Compiler.new(node) end let :scope do Puppet::Parser::Scope.new(compiler) end def with_file_content(content) path = tmpfile('file-function') file = File.new(path, 'wb') file.sync = true file.print content yield path end it "should read a file" do with_file_content('file content') do |name| expect(scope.function_file([name])).to eq("file content") end end it "should read a file keeping line endings intact" do with_file_content("file content\r\n") do |name| expect(scope.function_file([name])).to eq("file content\r\n") end end it "should read a file from a module path" do with_file_content('file content') do |name| mod = double('module') allow(mod).to receive(:file).with('myfile').and_return(name) allow(compiler.environment).to receive(:module).with('mymod').and_return(mod) expect(scope.function_file(['mymod/myfile'])).to eq('file content') end end it "should return the first file if given two files with absolute paths" do with_file_content('one') do |one| with_file_content('two') do |two| expect(scope.function_file([one, two])).to eq("one") end end end it "should return the first file if given two files with module paths" do with_file_content('one') do |one| with_file_content('two') do |two| mod = double('module') expect(compiler.environment).to receive(:module).with('mymod').and_return(mod) expect(mod).to receive(:file).with('one').and_return(one) allow(mod).to receive(:file).with('two').and_return(two) expect(scope.function_file(['mymod/one','mymod/two'])).to eq('one') end end end it "should return the first file if given two files with mixed paths, absolute first" do with_file_content('one') do |one| with_file_content('two') do |two| mod = double('module') allow(compiler.environment).to receive(:module).with('mymod').and_return(mod) allow(mod).to receive(:file).with('two').and_return(two) expect(scope.function_file([one,'mymod/two'])).to eq('one') end end end it "should return the first file if given two files with mixed paths, module first" do with_file_content('one') do |one| with_file_content('two') do |two| mod = double('module') expect(compiler.environment).to receive(:module).with('mymod').and_return(mod) allow(mod).to receive(:file).with('two').and_return(two) expect(scope.function_file(['mymod/two',one])).to eq('two') end end end it "should not fail when some files are absent" do expect { with_file_content('one') do |one| expect(scope.function_file([make_absolute("/should-not-exist"), one])).to eq('one') end }.to_not raise_error end it "should fail when all files are absent" do expect { scope.function_file([File.expand_path('one')]) }.to raise_error(Puppet::ParseError, /Could not find any files/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/shellquote_spec.rb
spec/unit/parser/functions/shellquote_spec.rb
require 'spec_helper' describe "the shellquote function" do let :node do Puppet::Node.new('localhost') end let :compiler do Puppet::Parser::Compiler.new(node) end let :scope do Puppet::Parser::Scope.new(compiler) end it "should exist" do expect(Puppet::Parser::Functions.function("shellquote")).to eq("function_shellquote") end it "should handle no arguments" do expect(scope.function_shellquote([])).to eq("") end it "should handle several simple arguments" do expect(scope.function_shellquote( ['foo', 'bar@example.com', 'localhost:/dev/null', 'xyzzy+-4711,23'] )).to eq('foo bar@example.com localhost:/dev/null xyzzy+-4711,23') end it "should handle array arguments" do expect(scope.function_shellquote( ['foo', ['bar@example.com', 'localhost:/dev/null'], 'xyzzy+-4711,23'] )).to eq('foo bar@example.com localhost:/dev/null xyzzy+-4711,23') end it "should quote unsafe characters" do expect(scope.function_shellquote(['/etc/passwd ', '(ls)', '*', '[?]', "'&'"])). to eq('"/etc/passwd " "(ls)" "*" "[?]" "\'&\'"') end it "should deal with double quotes" do expect(scope.function_shellquote(['"foo"bar"'])).to eq('\'"foo"bar"\'') end it "should cope with dollar signs" do expect(scope.function_shellquote(['$PATH', 'foo$bar', '"x$"'])). to eq("'$PATH' 'foo$bar' '\"x$\"'") end it "should deal with apostrophes (single quotes)" do expect(scope.function_shellquote(["'foo'bar'", "`$'EDITOR'`"])). to eq('"\'foo\'bar\'" "\\`\\$\'EDITOR\'\\`"') end it "should cope with grave accents (backquotes)" do expect(scope.function_shellquote(['`echo *`', '`ls "$MAILPATH"`'])). to eq("'`echo *`' '`ls \"$MAILPATH\"`'") end it "should deal with both single and double quotes" do expect(scope.function_shellquote(['\'foo"bar"xyzzy\'', '"foo\'bar\'xyzzy"'])). to eq('"\'foo\\"bar\\"xyzzy\'" "\\"foo\'bar\'xyzzy\\""') end it "should handle multiple quotes *and* dollars and backquotes" do expect(scope.function_shellquote(['\'foo"$x`bar`"xyzzy\''])). to eq('"\'foo\\"\\$x\\`bar\\`\\"xyzzy\'"') end it "should handle linefeeds" do expect(scope.function_shellquote(["foo \n bar"])).to eq("\"foo \n bar\"") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/sprintf_spec.rb
spec/unit/parser/functions/sprintf_spec.rb
require 'spec_helper' describe "the sprintf function" do before :each do node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) @scope = Puppet::Parser::Scope.new(compiler) end it "should exist" do expect(Puppet::Parser::Functions.function("sprintf")).to eq("function_sprintf") end it "should raise an ArgumentError if there is less than 1 argument" do expect { @scope.function_sprintf([]) }.to( raise_error(ArgumentError)) end it "should format integers" do result = @scope.function_sprintf(["%+05d", "23"]) expect(result).to(eql("+0023")) end it "should format floats" do result = @scope.function_sprintf(["%+.2f", "2.7182818284590451"]) expect(result).to(eql("+2.72")) end it "should format large floats" do result = @scope.function_sprintf(["%+.2e", "27182818284590451"]) str = "+2.72e+16" expect(result).to(eql(str)) end it "should perform more complex formatting" do result = @scope.function_sprintf( [ "<%.8s:%#5o %#8X (%-8s)>", "overlongstring", "23", "48879", "foo" ]) expect(result).to(eql("<overlong: 027 0XBEEF (foo )>")) end it 'does not attempt to mutate its arguments' do args = ['%d', 1].freeze expect { @scope.function_sprintf(args) }.to_not raise_error end it 'support named arguments in a hash with string keys' do result = @scope.function_sprintf(["%<foo>d : %<bar>f", {'foo' => 1, 'bar' => 2}]) expect(result).to eq("1 : 2.000000") end it 'raises a key error if a key is not present' do expect do @scope.function_sprintf(["%<foo>d : %<zanzibar>f", {'foo' => 1, 'bar' => 2}]) end.to raise_error(KeyError, /key<zanzibar> not found/) end it 'a hash with string keys that is output formats as strings' do result = @scope.function_sprintf(["%s", {'foo' => 1, 'bar' => 2}]) expect(result).to match(/{"foo"\s*=>\s*1, "bar"\s*=>\s*2}/) end it 'named arguments hash with non string keys are tolerated' do result = @scope.function_sprintf(["%<foo>d : %<bar>f", {'foo' => 1, 'bar' => 2, 1 => 2, [1] => 2, false => true, {} => {}}]) expect(result).to eq("1 : 2.000000") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/generate_spec.rb
spec/unit/parser/functions/generate_spec.rb
require 'spec_helper' def with_executor return yield unless Puppet::Util::Platform.jruby? begin Puppet::Util::ExecutionStub.set do |command, options, stdin, stdout, stderr| require 'open3' # simulate what puppetserver does Dir.chdir(options[:cwd]) do out, err, _status = Open3.capture3(*command) stdout.write(out) stderr.write(err) # execution api expects stdout to be returned out end end yield ensure Puppet::Util::ExecutionStub.reset end end describe "the generate function" do include PuppetSpec::Files let :node do Puppet::Node.new('localhost') end let :compiler do Puppet::Parser::Compiler.new(node) end let :scope do Puppet::Parser::Scope.new(compiler) end let :cwd do tmpdir('generate') end it "should exist" do expect(Puppet::Parser::Functions.function("generate")).to eq("function_generate") end it "accept a fully-qualified path as a command" do command = File.expand_path('/command/foo') expect(Puppet::Util::Execution).to receive(:execute).with([command], anything).and_return("yay") expect(scope.function_generate([command])).to eq("yay") end it "should not accept a relative path as a command" do expect { scope.function_generate(["command"]) }.to raise_error(Puppet::ParseError) end it "should not accept a command containing illegal characters" do expect { scope.function_generate([File.expand_path('/##/command')]) }.to raise_error(Puppet::ParseError) end it "should not accept a command containing spaces" do expect { scope.function_generate([File.expand_path('/com mand')]) }.to raise_error(Puppet::ParseError) end it "should not accept a command containing '..'", :unless => RUBY_PLATFORM == 'java' do command = File.expand_path("/command/../") expect { scope.function_generate([command]) }.to raise_error(Puppet::ParseError) end it "should execute the generate script with the correct working directory" do command = File.expand_path("/usr/local/command") expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: %r{/usr/local})).and_return("yay") scope.function_generate([command]) end it "should execute the generate script with failonfail" do command = File.expand_path("/usr/local/command") expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(failonfail: true)).and_return("yay") scope.function_generate([command]) end it "should execute the generate script with combine" do command = File.expand_path("/usr/local/command") expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(combine: true)).and_return("yay") scope.function_generate([command]) end it "executes a command in a working directory" do if Puppet::Util::Platform.windows? command = File.join(cwd, 'echo.bat') File.write(command, <<~END) @echo off echo %CD% END expect(scope.function_generate([command]).chomp).to match(cwd.gsub('/', '\\')) else with_executor do command = File.join(cwd, 'echo.sh') File.write(command, <<~END) #!/bin/sh echo $PWD END Puppet::FileSystem.chmod(0755, command) # Using a matcher to avoid /var vs. /private/var shenanigans on MacOS expect(scope.function_generate([command]).chomp).to match(/#{cwd}/) end end end describe "on Windows", :if => Puppet::Util::Platform.windows? do it "should accept the tilde in the path" do command = "C:/DOCUME~1/ADMINI~1/foo.bat" expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: "C:/DOCUME~1/ADMINI~1")).and_return("yay") expect(scope.function_generate([command])).to eq('yay') end it "should accept lower-case drive letters" do command = 'd:/command/foo' expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: "d:/command")).and_return("yay") expect(scope.function_generate([command])).to eq('yay') end it "should accept upper-case drive letters" do command = 'D:/command/foo' expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: "D:/command")).and_return("yay") expect(scope.function_generate([command])).to eq('yay') end it "should accept forward and backslashes in the path" do command = 'D:\command/foo\bar' expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: 'D:\command/foo')).and_return("yay") expect(scope.function_generate([command])).to eq('yay') end it "should reject colons when not part of the drive letter" do expect { scope.function_generate(['C:/com:mand']) }.to raise_error(Puppet::ParseError) end it "should reject root drives" do expect { scope.function_generate(['C:/']) }.to raise_error(Puppet::ParseError) end end describe "on POSIX", :if => Puppet.features.posix? do it "should reject backslashes" do expect { scope.function_generate(['/com\\mand']) }.to raise_error(Puppet::ParseError) end it "should accept plus and dash" do command = "/var/folders/9z/9zXImgchH8CZJh6SgiqS2U+++TM/-Tmp-/foo" expect(Puppet::Util::Execution).to receive(:execute).with([command], hash_including(cwd: '/var/folders/9z/9zXImgchH8CZJh6SgiqS2U+++TM/-Tmp-')).and_return("yay") expect(scope.function_generate([command])).to eq('yay') end end describe "function_generate", :unless => RUBY_PLATFORM == 'java' do let :command do script_containing('function_generate', :windows => '@echo off' + "\n" + 'echo a-%1 b-%2', :posix => '#!/bin/sh' + "\n" + 'echo a-$1 b-$2') end after :each do File.delete(command) if Puppet::FileSystem.exist?(command) end it "returns the output as a String" do expect(scope.function_generate([command]).class).to eq(String) end it "should call generator with no arguments" do expect(scope.function_generate([command])).to eq("a- b-\n") end it "should call generator with one argument" do expect(scope.function_generate([command, 'one'])).to eq("a-one b-\n") end it "should call generator with wo arguments" do expect(scope.function_generate([command, 'one', 'two'])).to eq("a-one b-two\n") end it "should fail if generator is not absolute" do expect { scope.function_generate(['boo']) }.to raise_error(Puppet::ParseError) end it "should fail if generator fails" do expect { scope.function_generate(['/boo']) }.to raise_error(Puppet::ParseError) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/hiera_spec.rb
spec/unit/parser/functions/hiera_spec.rb
require 'spec_helper' require 'puppet_spec/scope' describe 'Puppet::Parser::Functions#hiera' do include PuppetSpec::Scope let :scope do create_test_scope_for_node('foo') end it 'should raise an error since this function is converted to 4x API)' do expect { scope.function_hiera(['key']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/fail_spec.rb
spec/unit/parser/functions/fail_spec.rb
require 'spec_helper' describe "the 'fail' parser function" do let :scope do node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) scope = Puppet::Parser::Scope.new(compiler) allow(scope).to receive(:environment).and_return(nil) scope end it "should exist" do expect(Puppet::Parser::Functions.function(:fail)).to eq("function_fail") end it "should raise a parse error if invoked" do expect { scope.function_fail([]) }.to raise_error Puppet::ParseError end it "should join arguments into a string in the error" do expect { scope.function_fail(["hello", "world"]) }.to raise_error(/hello world/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/hiera_array_spec.rb
spec/unit/parser/functions/hiera_array_spec.rb
require 'spec_helper' require 'puppet_spec/scope' describe 'Puppet::Parser::Functions#hiera_array' do include PuppetSpec::Scope let :scope do create_test_scope_for_node('foo') end it 'should raise an error since this function is converted to 4x API)' do expect { scope.function_hiera_array(['key']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/versioncmp_spec.rb
spec/unit/parser/functions/versioncmp_spec.rb
require 'spec_helper' describe "the versioncmp function" do before :each do node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) @scope = Puppet::Parser::Scope.new(compiler) end it "should exist" do expect(Puppet::Parser::Functions.function("versioncmp")).to eq("function_versioncmp") end it "should raise an ArgumentError if there is less than 2 arguments" do expect { @scope.function_versioncmp(["1.2"]) }.to raise_error(ArgumentError) end it "should raise an ArgumentError if there is more than 2 arguments" do expect { @scope.function_versioncmp(["1.2", "2.4.5", "3.5.6"]) }.to raise_error(ArgumentError) end it "should call Puppet::Util::Package.versioncmp (included in scope)" do expect(Puppet::Util::Package).to receive(:versioncmp).with("1.2", "1.3").and_return(-1) @scope.function_versioncmp(["1.2", "1.3"]) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/hiera_include_spec.rb
spec/unit/parser/functions/hiera_include_spec.rb
require 'spec_helper' require 'puppet_spec/scope' describe 'Puppet::Parser::Functions#hiera_include' do include PuppetSpec::Scope let :scope do create_test_scope_for_node('foo') end it 'should raise an error since this function is converted to 4x API)' do expect { scope.function_hiera_include(['key']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/hiera_hash_spec.rb
spec/unit/parser/functions/hiera_hash_spec.rb
require 'spec_helper' require 'puppet_spec/scope' describe 'Puppet::Parser::Functions#hiera_hash' do include PuppetSpec::Scope let :scope do create_test_scope_for_node('foo') end it 'should raise an error since this function is converted to 4x API)' do expect { scope.function_hiera_hash(['key']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/scanf_spec.rb
spec/unit/parser/functions/scanf_spec.rb
require 'spec_helper' describe "the scanf function" do let(:node) { Puppet::Node.new('localhost') } let(:compiler) { Puppet::Parser::Compiler.new(node) } let(:scope) { Puppet::Parser::Scope.new(compiler) } it 'scans a value and returns an array' do expect(scope.function_scanf(['42', '%i'])[0] == 42) end it 'returns empty array if nothing was scanned' do expect(scope.function_scanf(['no', '%i']) == []) end it 'produces result up to first unsuccessful scan' do expect(scope.function_scanf(['42 no', '%i'])[0] == 42) end it 'errors when not given enough arguments' do expect do scope.function_scanf(['42']) end.to raise_error(/.*scanf\(\): Wrong number of arguments given/m) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/create_resources_spec.rb
spec/unit/parser/functions/create_resources_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'puppet_spec/files' describe 'function for dynamically creating resources' do include PuppetSpec::Compiler include PuppetSpec::Files before :each do node = Puppet::Node.new("floppy", :environment => 'production') @compiler = Puppet::Parser::Compiler.new(node) @scope = Puppet::Parser::Scope.new(@compiler) @topscope = @scope.compiler.topscope @scope.parent = @topscope Puppet::Parser::Functions.function(:create_resources) end it "should exist" do expect(Puppet::Parser::Functions.function(:create_resources)).to eq("function_create_resources") end it 'should require two or three arguments' do expect { @scope.function_create_resources(['foo']) }.to raise_error(ArgumentError, 'create_resources(): Wrong number of arguments given (1 for minimum 2)') expect { @scope.function_create_resources(['foo', 'bar', 'blah', 'baz']) }.to raise_error(ArgumentError, 'create_resources(): wrong number of arguments (4; must be 2 or 3)') end it 'should require second argument to be a hash' do expect { @scope.function_create_resources(['foo','bar']) }.to raise_error(ArgumentError, 'create_resources(): second argument must be a hash') end it 'should require optional third argument to be a hash' do expect { @scope.function_create_resources(['foo',{},'foo']) }.to raise_error(ArgumentError, 'create_resources(): third argument, if provided, must be a hash') end context 'when being called from a manifest in a file' do let(:dir) do dir_containing('manifests', { 'site.pp' => <<-EOF # comment here to make the call be on a particular # source line (3) create_resources('notify', { 'a' => { 'message'=>'message a'}, 'b' => { 'message'=>'message b'}, } ) EOF } ) end it 'file and line information where call originates is written to all resources created in one call' do node = Puppet::Node.new('test') file = File.join(dir, 'site.pp') Puppet[:manifest] = file catalog = Puppet::Parser::Compiler.compile(node).filter { |r| r.virtual? } expect(catalog.resource(:notify, 'a').file).to eq(file) expect(catalog.resource(:notify, 'a').line).to eq(3) expect(catalog.resource(:notify, 'b').file).to eq(file) expect(catalog.resource(:notify, 'b').line).to eq(3) end end describe 'when creating native types' do it 'empty hash should not cause resources to be added' do noop_catalog = compile_to_catalog("create_resources('file', {})") empty_catalog = compile_to_catalog("") expect(noop_catalog.resources.size).to eq(empty_catalog.resources.size) end it 'should be able to add' do catalog = compile_to_catalog("create_resources('file', {'/etc/foo'=>{'ensure'=>'present'}})") expect(catalog.resource(:file, "/etc/foo")['ensure']).to eq('present') end it 'should pick up and pass on file and line information' do # mock location as the compile_to_catalog sets Puppet[:code} which does not # have file/line support. expect(Puppet::Pops::PuppetStack).to receive(:top_of_stack).once.and_return(['test.pp', 1234]) catalog = compile_to_catalog("create_resources('file', {'/etc/foo'=>{'ensure'=>'present'}})") r = catalog.resource(:file, "/etc/foo") expect(r.file).to eq('test.pp') expect(r.line).to eq(1234) end it 'should be able to add virtual resources' do catalog = compile_to_catalog("create_resources('@file', {'/etc/foo'=>{'ensure'=>'present'}})\nrealize(File['/etc/foo'])") expect(catalog.resource(:file, "/etc/foo")['ensure']).to eq('present') end it 'unrealized exported resources should not be added' do # a compiled catalog is normally filtered on virtual resources # here the compilation is performed unfiltered to be able to find the exported resource # it is then asserted that the exported resource is also virtual (and therefore filtered out by a real compilation). catalog = compile_to_catalog_unfiltered("create_resources('@@file', {'/etc/foo'=>{'ensure'=>'present'}})") expect(catalog.resource(:file, "/etc/foo").exported).to eq(true) expect(catalog.resource(:file, "/etc/foo").virtual).to eq(true) end it 'should be able to add exported resources' do catalog = compile_to_catalog("create_resources('@@file', {'/etc/foo'=>{'ensure'=>'present'}}) realize(File['/etc/foo'])") expect(catalog.resource(:file, "/etc/foo")['ensure']).to eq('present') expect(catalog.resource(:file, "/etc/foo").exported).to eq(true) end it 'should accept multiple resources' do catalog = compile_to_catalog("create_resources('notify', {'foo'=>{'message'=>'one'}, 'bar'=>{'message'=>'two'}})") expect(catalog.resource(:notify, "foo")['message']).to eq('one') expect(catalog.resource(:notify, "bar")['message']).to eq('two') end it 'should fail to add non-existing resource type' do expect do @scope.function_create_resources(['create-resource-foo', { 'foo' => {} }]) end.to raise_error(/Unknown resource type: 'create-resource-foo'/) end it 'should be able to add edges' do rg = compile_to_relationship_graph("notify { test: }\n create_resources('notify', {'foo'=>{'require'=>'Notify[test]'}})") test = rg.vertices.find { |v| v.title == 'test' } foo = rg.vertices.find { |v| v.title == 'foo' } expect(test).to be expect(foo).to be expect(rg.path_between(test,foo)).to be end it 'should filter out undefined edges as they cause errors' do rg = compile_to_relationship_graph("notify { test: }\n create_resources('notify', {'foo'=>{'require'=>undef}})") test = rg.vertices.find { |v| v.title == 'test' } foo = rg.vertices.find { |v| v.title == 'foo' } expect(test).to be expect(foo).to be expect(rg.path_between(foo,nil)).to_not be end it 'should filter out undefined edges in an array as they cause errors' do rg = compile_to_relationship_graph("notify { test: }\n create_resources('notify', {'foo'=>{'require'=>[undef]}})") test = rg.vertices.find { |v| v.title == 'test' } foo = rg.vertices.find { |v| v.title == 'foo' } expect(test).to be expect(foo).to be expect(rg.path_between(foo,nil)).to_not be end it 'should account for default values' do catalog = compile_to_catalog("create_resources('file', {'/etc/foo'=>{'ensure'=>'present'}, '/etc/baz'=>{'group'=>'food'}}, {'group' => 'bar'})") expect(catalog.resource(:file, "/etc/foo")['group']).to eq('bar') expect(catalog.resource(:file, "/etc/baz")['group']).to eq('food') end end describe 'when dynamically creating resource types' do it 'should be able to create defined resource types' do catalog = compile_to_catalog(<<-MANIFEST) define foocreateresource($one) { notify { $name: message => $one } } create_resources('foocreateresource', {'blah'=>{'one'=>'two'}}) MANIFEST expect(catalog.resource(:notify, "blah")['message']).to eq('two') end it 'should fail if defines are missing params' do expect { compile_to_catalog(<<-MANIFEST) define foocreateresource($one) { notify { $name: message => $one } } create_resources('foocreateresource', {'blah'=>{}}) MANIFEST }.to raise_error(Puppet::Error, /Foocreateresource\[blah\]: expects a value for parameter 'one'/) end it 'should accept undef as explicit value when parameter has no default value' do catalog = compile_to_catalog(<<-MANIFEST) define foocreateresource($one) { notify { $name: message => "aaa${one}bbb" } } create_resources('foocreateresource', {'blah'=>{ one => undef}}) MANIFEST expect(catalog.resource(:notify, "blah")['message']).to eq('aaabbb') end it 'should use default value expression if given value is undef' do catalog = compile_to_catalog(<<-MANIFEST) define foocreateresource($one = 'xx') { notify { $name: message => "aaa${one}bbb" } } create_resources('foocreateresource', {'blah'=>{ one => undef}}) MANIFEST expect(catalog.resource(:notify, "blah")['message']).to eq('aaaxxbbb') end it 'should be able to add multiple defines' do catalog = compile_to_catalog(<<-MANIFEST) define foocreateresource($one) { notify { $name: message => $one } } create_resources('foocreateresource', {'blah'=>{'one'=>'two'}, 'blaz'=>{'one'=>'three'}}) MANIFEST expect(catalog.resource(:notify, "blah")['message']).to eq('two') expect(catalog.resource(:notify, "blaz")['message']).to eq('three') end it 'should be able to add edges' do rg = compile_to_relationship_graph(<<-MANIFEST) define foocreateresource($one) { notify { $name: message => $one } } notify { test: } create_resources('foocreateresource', {'blah'=>{'one'=>'two', 'require' => 'Notify[test]'}}) MANIFEST test = rg.vertices.find { |v| v.title == 'test' } blah = rg.vertices.find { |v| v.title == 'blah' } expect(test).to be expect(blah).to be expect(rg.path_between(test,blah)).to be end it 'should account for default values' do catalog = compile_to_catalog(<<-MANIFEST) define foocreateresource($one) { notify { $name: message => $one } } create_resources('foocreateresource', {'blah'=>{}}, {'one' => 'two'}) MANIFEST expect(catalog.resource(:notify, "blah")['message']).to eq('two') end end describe 'when creating classes' do let(:logs) { [] } let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } } it 'should be able to create classes' do catalog = compile_to_catalog(<<-MANIFEST) class bar($one) { notify { test: message => $one } } create_resources('class', {'bar'=>{'one'=>'two'}}) MANIFEST expect(catalog.resource(:notify, "test")['message']).to eq('two') expect(catalog.resource(:class, "bar")).not_to be_nil end it 'should error if class is exported' do expect{ compile_to_catalog('class test{} create_resources("@@class", {test => {}})') }.to raise_error(/Classes are not virtualizable/) end it 'should error if class is virtual' do expect{ compile_to_catalog('class test{} create_resources("@class", {test => {}})') }.to raise_error(/Classes are not virtualizable/) end it 'should be able to add edges' do rg = compile_to_relationship_graph(<<-MANIFEST) class bar($one) { notify { test: message => $one } } notify { tester: } create_resources('class', {'bar'=>{'one'=>'two', 'require' => 'Notify[tester]'}}) MANIFEST test = rg.vertices.find { |v| v.title == 'test' } tester = rg.vertices.find { |v| v.title == 'tester' } expect(test).to be expect(tester).to be expect(rg.path_between(tester,test)).to be end it 'should account for default values' do catalog = compile_to_catalog(<<-MANIFEST) class bar($one) { notify { test: message => $one } } create_resources('class', {'bar'=>{}}, {'one' => 'two'}) MANIFEST expect(catalog.resource(:notify, "test")['message']).to eq('two') expect(catalog.resource(:class, "bar")).not_to be_nil end it 'should fail with a correct error message if the syntax of an imported file is incorrect' do expect{ Puppet[:modulepath] = my_fixture_dir compile_to_catalog('include foo') }.to raise_error(Puppet::Error, /Syntax error at.*/) end it 'is not available when --tasks is on' do Puppet[:tasks] = true expect do compile_to_catalog(<<-MANIFEST) create_resources('class', {'bar'=>{}}, {'one' => 'two'}) MANIFEST end.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/) end end def collect_notices(code) Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compile_to_catalog(code) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/fqdn_rand_spec.rb
spec/unit/parser/functions/fqdn_rand_spec.rb
require 'spec_helper' require 'puppet_spec/scope' describe "the fqdn_rand function" do include PuppetSpec::Scope it "returns an integer" do expect(fqdn_rand(3)).to be_an(Integer) end it "provides a random number strictly less than the given max" do expect(fqdn_rand(3)).to satisfy {|n| n < 3 } end it "provides the same 'random' value on subsequent calls for the same host" do expect(fqdn_rand(3)).to eql(fqdn_rand(3)) end it "considers the same host and same extra arguments to have the same random sequence" do first_random = fqdn_rand(3, :extra_identifier => [1, "same", "host"]) second_random = fqdn_rand(3, :extra_identifier => [1, "same", "host"]) expect(first_random).to eql(second_random) end it "allows extra arguments to control the random value on a single host" do first_random = fqdn_rand(10000, :extra_identifier => [1, "different", "host"]) second_different_random = fqdn_rand(10000, :extra_identifier => [2, "different", "host"]) expect(first_random).not_to eql(second_different_random) end it "should return different sequences of value for different hosts" do val1 = fqdn_rand(1000000000, :host => "first.host.com") val2 = fqdn_rand(1000000000, :host => "second.host.com") expect(val1).not_to eql(val2) end it "should return a specific value with given set of inputs on non-fips enabled host" do allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(false) expect(fqdn_rand(3000, :host => 'dummy.fqdn.net')).to eql(338) end it "should return a specific value with given set of inputs on fips enabled host" do allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true) expect(fqdn_rand(3000, :host => 'dummy.fqdn.net')).to eql(278) end it "should return a specific value with given seed on a non-fips enabled host" do allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(false) expect(fqdn_rand(5000, :extra_identifier => ['expensive job 33'])).to eql(3374) end it "should return a specific value with given seed on a fips enabled host" do allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true) expect(fqdn_rand(5000, :extra_identifier => ['expensive job 33'])).to eql(2389) end it "returns the same value if only host differs by case" do val1 = fqdn_rand(1000000000, :host => "host.example.com", :extra_identifier => [nil, true]) val2 = fqdn_rand(1000000000, :host => "HOST.example.com", :extra_identifier => [nil, true]) expect(val1).to eql(val2) end it "returns the same value if only host differs by case and an initial seed is given" do val1 = fqdn_rand(1000000000, :host => "host.example.com", :extra_identifier => ['a seed', true]) val2 = fqdn_rand(1000000000, :host => "HOST.example.com", :extra_identifier => ['a seed', true]) expect(val1).to eql(val2) end def fqdn_rand(max, args = {}) host = args[:host] || '127.0.0.1' extra = args[:extra_identifier] || [] scope = create_test_scope_for_node('localhost') scope.set_facts({ 'networking' => { 'fqdn' => host }}) scope.function_fqdn_rand([max] + extra) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/split_spec.rb
spec/unit/parser/functions/split_spec.rb
require 'spec_helper' describe "the split function" do before :each do node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) @scope = Puppet::Parser::Scope.new(compiler) end it 'should raise a ParseError' do expect { @scope.function_split([ '130;236;254;10', ';']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/inline_template_spec.rb
spec/unit/parser/functions/inline_template_spec.rb
require 'spec_helper' describe "the inline_template function" do let(:node) { Puppet::Node.new('localhost') } let(:compiler) { Puppet::Parser::Compiler.new(node) } let(:scope) { Puppet::Parser::Scope.new(compiler) } it "should concatenate template wrapper outputs for multiple templates" do expect(inline_template("template1", "template2")).to eq("template1template2") end it "should raise an error if the template raises an error" do expect { inline_template("<% raise 'error' %>") }.to raise_error(Puppet::ParseError) end it "is not interfered with by a variable called 'string' (#14093)" do scope['string'] = "this is a variable" expect(inline_template("this is a template")).to eq("this is a template") end it "has access to a variable called 'string' (#14093)" do scope['string'] = "this is a variable" expect(inline_template("string was: <%= @string %>")).to eq("string was: this is a variable") end it 'is not available when --tasks is on' do Puppet[:tasks] = true expect { inline_template("<%= lookupvar('myvar') %>") }.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/) end def inline_template(*templates) scope.function_inline_template(templates) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/tagged_spec.rb
spec/unit/parser/functions/tagged_spec.rb
require 'spec_helper' describe "the 'tagged' function" do before :each do node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) @scope = Puppet::Parser::Scope.new(compiler) end it "should exist" do expect(Puppet::Parser::Functions.function(:tagged)).to eq("function_tagged") end it 'is not available when --tasks is on' do Puppet[:tasks] = true expect do @scope.function_tagged(['one', 'two']) end.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/) end it 'should be case-insensitive' do resource = Puppet::Parser::Resource.new(:file, "/file", :scope => @scope) allow(@scope).to receive(:resource).and_return(resource) @scope.function_tag ["one"] expect(@scope.function_tagged(['One'])).to eq(true) end it 'should check if all specified tags are included' do resource = Puppet::Parser::Resource.new(:file, "/file", :scope => @scope) allow(@scope).to receive(:resource).and_return(resource) @scope.function_tag ["one"] expect(@scope.function_tagged(['one', 'two'])).to eq(false) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/digest_spec.rb
spec/unit/parser/functions/digest_spec.rb
require 'spec_helper' describe "the digest function", :uses_checksums => true do before :each do n = Puppet::Node.new('unnamed') c = Puppet::Parser::Compiler.new(n) @scope = Puppet::Parser::Scope.new(c) end it "should exist" do expect(Puppet::Parser::Functions.function("digest")).to eq("function_digest") end with_digest_algorithms do it "should use the proper digest function" do result = @scope.function_digest([plaintext]) expect(result).to(eql( checksum )) end it "should only accept one parameter" do expect do @scope.function_digest(['foo', 'bar']) end.to raise_error(ArgumentError) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/lookup_spec.rb
spec/unit/parser/functions/lookup_spec.rb
require 'spec_helper' require 'puppet/pops' require 'stringio' require 'puppet_spec/scope' describe "lookup function" do include PuppetSpec::Scope let :scope do create_test_scope_for_node('foo') end it 'should raise an error since this function is converted to 4x API)' do expect { scope.function_lookup(['key']) }.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/tag_spec.rb
spec/unit/parser/functions/tag_spec.rb
require 'spec_helper' describe "the 'tag' function" do before :each do node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) @scope = Puppet::Parser::Scope.new(compiler) end it "should exist" do expect(Puppet::Parser::Functions.function(:tag)).to eq("function_tag") end it "should tag the resource with any provided tags" do resource = Puppet::Parser::Resource.new(:file, "/file", :scope => @scope) expect(@scope).to receive(:resource).and_return(resource) @scope.function_tag ["one", "two"] expect(resource).to be_tagged("one") expect(resource).to be_tagged("two") end it 'is not available when --tasks is on' do Puppet[:tasks] = true expect do @scope.function_tag(['one', 'two']) end.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/realize_spec.rb
spec/unit/parser/functions/realize_spec.rb
require 'spec_helper' require 'matchers/resource' require 'puppet_spec/compiler' describe "the realize function" do include Matchers::Resource include PuppetSpec::Compiler it "realizes a single, referenced resource" do catalog = compile_to_catalog(<<-EOM) @notify { testing: } realize(Notify[testing]) EOM expect(catalog).to have_resource("Notify[testing]") end it "realizes multiple resources" do catalog = compile_to_catalog(<<-EOM) @notify { testing: } @notify { other: } realize(Notify[testing], Notify[other]) EOM expect(catalog).to have_resource("Notify[testing]") expect(catalog).to have_resource("Notify[other]") end it "realizes resources provided in arrays" do catalog = compile_to_catalog(<<-EOM) @notify { testing: } @notify { other: } realize([Notify[testing], [Notify[other]]]) EOM expect(catalog).to have_resource("Notify[testing]") expect(catalog).to have_resource("Notify[other]") end it "fails when the resource does not exist" do expect do compile_to_catalog(<<-EOM) realize(Notify[missing]) EOM end.to raise_error(Puppet::Error, /Failed to realize/) end it "fails when no parameters given" do expect do compile_to_catalog(<<-EOM) realize() EOM end.to raise_error(Puppet::Error, /Wrong number of arguments/) end it "silently does nothing when an empty array of resources is given" do compile_to_catalog(<<-EOM) realize([]) EOM end it 'is not available when --tasks is on' do Puppet[:tasks] = true expect do compile_to_catalog(<<-MANIFEST) realize([]) MANIFEST end.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/template_spec.rb
spec/unit/parser/functions/template_spec.rb
require 'spec_helper' describe "the template function" do let :node do Puppet::Node.new('localhost') end let :compiler do Puppet::Parser::Compiler.new(node) end let :scope do Puppet::Parser::Scope.new(compiler) end it "concatenates outputs for multiple templates" do tw1 = double("template_wrapper1") tw2 = double("template_wrapper2") allow(Puppet::Parser::TemplateWrapper).to receive(:new).and_return(tw1,tw2) allow(tw1).to receive(:file=).with("1") allow(tw2).to receive(:file=).with("2") allow(tw1).to receive(:result).and_return("result1") allow(tw2).to receive(:result).and_return("result2") expect(scope.function_template(["1","2"])).to eq("result1result2") end it "raises an error if the template raises an error" do tw = double('template_wrapper') allow(tw).to receive(:file=).with("1") allow(Puppet::Parser::TemplateWrapper).to receive(:new).and_return(tw) allow(tw).to receive(:result).and_raise expect { scope.function_template(["1"]) }.to raise_error(Puppet::ParseError, /Failed to parse template/) end context "when accessing scope variables via method calls (deprecated)" do it "raises an error when accessing an undefined variable" do expect { eval_template("template <%= deprecated %>") }.to raise_error(Puppet::ParseError, /undefined local variable or method.*deprecated'/) end it "looks up the value from the scope" do scope["deprecated"] = "deprecated value" expect { eval_template("template <%= deprecated %>")}.to raise_error(/undefined local variable or method.*deprecated'/) end it "still has access to Kernel methods" do expect { eval_template("<%= binding %>") }.to_not raise_error end end context "when accessing scope variables as instance variables" do it "has access to values" do scope['scope_var'] = "value" expect(eval_template("<%= @scope_var %>")).to eq("value") end it "get nil accessing a variable that does not exist" do expect(eval_template("<%= @not_defined.nil? %>")).to eq("true") end it "get nil accessing a variable that is undef" do scope['undef_var'] = :undef expect(eval_template("<%= @undef_var.nil? %>")).to eq("true") end end it "is not interfered with by having a variable named 'string' (#14093)" do scope['string'] = "this output should not be seen" expect(eval_template("some text that is static")).to eq("some text that is static") end it "has access to a variable named 'string' (#14093)" do scope['string'] = "the string value" expect(eval_template("string was: <%= @string %>")).to eq("string was: the string value") end it "does not have direct access to Scope#lookupvar" do expect { eval_template("<%= lookupvar('myvar') %>") }.to raise_error(Puppet::ParseError, /undefined method.*lookupvar'/) end it 'is not available when --tasks is on' do Puppet[:tasks] = true expect { eval_template("<%= lookupvar('myvar') %>") }.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/) end def eval_template(content) allow(Puppet::FileSystem).to receive(:read_preserve_line_endings).with("template").and_return(content) allow(Puppet::Parser::Files).to receive(:find_template).and_return("template") scope.function_template(['template']) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions/regsubst_spec.rb
spec/unit/parser/functions/regsubst_spec.rb
require 'spec_helper' describe "the regsubst function" do before :each do node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) @scope = Puppet::Parser::Scope.new(compiler) end it 'should raise an ParseError' do expect do @scope.function_regsubst( [ 'the monkey breaks banana trees', 'b[an]*a', 'coconut' ]) end.to raise_error(Puppet::ParseError, /can only be called using the 4.x function API/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/ast/block_expression_spec.rb
spec/unit/parser/ast/block_expression_spec.rb
require 'spec_helper' require 'puppet/parser/ast/block_expression' describe 'Puppet::Parser::AST::BlockExpression' do class StackDepthAST < Puppet::Parser::AST attr_reader :call_depth def evaluate(*options) @call_depth = caller.length end end NO_SCOPE = nil def depth_probe StackDepthAST.new end def sequence_probe(name) probe = double("Sequence Probe #{name}") expect(probe).to receive(:safeevaluate).ordered probe end def block_of(children) Puppet::Parser::AST::BlockExpression.new(:children => children) end def assert_all_at_same_depth(*probes) depth0 = probes[0].call_depth probes.drop(1).each do |p| expect(p.call_depth).to eq(depth0) end end it "evaluates all its children at the same stack depth" do depth_probes = [depth_probe, depth_probe] expr = block_of(depth_probes) expr.evaluate(NO_SCOPE) assert_all_at_same_depth(*depth_probes) end it "evaluates sequenced children at the same stack depth" do depth1 = depth_probe depth2 = depth_probe depth3 = depth_probe expr1 = block_of([depth1]) expr2 = block_of([depth2]) expr3 = block_of([depth3]) expr1.sequence_with(expr2).sequence_with(expr3).evaluate(NO_SCOPE) assert_all_at_same_depth(depth1, depth2, depth3) end it "evaluates sequenced children in order" do expr1 = block_of([sequence_probe("Step 1")]) expr2 = block_of([sequence_probe("Step 2")]) expr3 = block_of([sequence_probe("Step 3")]) expr1.sequence_with(expr2).sequence_with(expr3).evaluate(NO_SCOPE) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/ast/leaf_spec.rb
spec/unit/parser/ast/leaf_spec.rb
require 'spec_helper' describe Puppet::Parser::AST::Leaf do before :each do node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) @scope = Puppet::Parser::Scope.new(compiler) @value = double('value') @leaf = Puppet::Parser::AST::Leaf.new(:value => @value) end describe "when converting to string" do it "should transform its value to string" do value = double('value', :is_a? => true) expect(value).to receive(:to_s) Puppet::Parser::AST::Leaf.new( :value => value ).to_s end end it "should have a match method" do expect(@leaf).to respond_to(:match) end it "should delegate match to ==" do expect(@value).to receive(:==).with("value") @leaf.match("value") end end describe Puppet::Parser::AST::Regex do before :each do node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) @scope = Puppet::Parser::Scope.new(compiler) end describe "when initializing" do it "should create a Regexp with its content when value is not a Regexp" do expect(Regexp).to receive(:new).with("/ab/") Puppet::Parser::AST::Regex.new :value => "/ab/" end it "should not create a Regexp with its content when value is a Regexp" do value = Regexp.new("/ab/") expect(Regexp).not_to receive(:new).with("/ab/") Puppet::Parser::AST::Regex.new :value => value end end describe "when evaluating" do it "should return self" do val = Puppet::Parser::AST::Regex.new :value => "/ab/" expect(val.evaluate(@scope)).to be === val end end it 'should return the PRegexpType#regexp_to_s_with_delimiters with to_s' do regex = double('regex') allow(Regexp).to receive(:new).and_return(regex) val = Puppet::Parser::AST::Regex.new :value => '/ab/' expect(Puppet::Pops::Types::PRegexpType).to receive(:regexp_to_s_with_delimiters) val.to_s end it "should delegate match to the underlying regexp match method" do regex = Regexp.new("/ab/") val = Puppet::Parser::AST::Regex.new :value => regex expect(regex).to receive(:match).with("value") val.match("value") end end describe Puppet::Parser::AST::HostName do before :each do node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) @scope = Puppet::Parser::Scope.new(compiler) @value = 'value' allow(@value).to receive(:to_s).and_return(@value) allow(@value).to receive(:downcase).and_return(@value) @host = Puppet::Parser::AST::HostName.new(:value => @value) end it "should raise an error if hostname is not valid" do expect { Puppet::Parser::AST::HostName.new( :value => "not a hostname!" ) }.to raise_error(Puppet::DevError, /'not a hostname!' is not a valid hostname/) end it "should not raise an error if hostname is a regex" do expect { Puppet::Parser::AST::HostName.new( :value => Puppet::Parser::AST::Regex.new(:value => "/test/") ) }.not_to raise_error end it "should stringify the value" do value = double('value', :=~ => false) expect(value).to receive(:to_s).and_return("test") Puppet::Parser::AST::HostName.new(:value => value) end it "should downcase the value" do value = double('value', :=~ => false) allow(value).to receive(:to_s).and_return("UPCASED") host = Puppet::Parser::AST::HostName.new(:value => value) host.value == "upcased" end it "should evaluate to its value" do expect(@host.evaluate(@scope)).to eq(@value) end it "should delegate eql? to the underlying value if it is an HostName" do expect(@value).to receive(:eql?).with("value") @host.eql?("value") end it "should delegate eql? to the underlying value if it is not an HostName" do value = double('compared', :is_a? => true, :value => "value") expect(@value).to receive(:eql?).with("value") @host.eql?(value) end it "should delegate hash to the underlying value" do expect(@value).to receive(:hash) @host.hash end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/other/selinux_spec.rb
spec/unit/other/selinux_spec.rb
require 'spec_helper' describe Puppet::Type.type(:file), " when manipulating file contexts" do include PuppetSpec::Files before :each do @file = Puppet::Type::File.new( :name => make_absolute("/tmp/foo"), :ensure => "file", :seluser => "user_u", :selrole => "role_r", :seltype => "type_t") end it "should use :seluser to get/set an SELinux user file context attribute" do expect(@file[:seluser]).to eq("user_u") end it "should use :selrole to get/set an SELinux role file context attribute" do expect(@file[:selrole]).to eq("role_r") end it "should use :seltype to get/set an SELinux user file context attribute" do expect(@file[:seltype]).to eq("type_t") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/context/trusted_information_spec.rb
spec/unit/context/trusted_information_spec.rb
require 'spec_helper' require 'puppet/certificate_factory' require 'puppet/context/trusted_information' describe Puppet::Context::TrustedInformation, :unless => RUBY_PLATFORM == 'java' do let(:key) { OpenSSL::PKey::RSA.new(Puppet[:keylength]) } let(:csr) do csr = Puppet::SSL::CertificateRequest.new("csr") csr.generate(key, :extension_requests => { '1.3.6.1.4.1.15.1.2.1' => 'Ignored CSR extension', '1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info', '1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info', }) csr end let(:cert) do cert = Puppet::SSL::Certificate.from_instance(Puppet::CertificateFactory.build('ca', csr, csr.content, 1)) # The cert must be signed so that it can be successfully be DER-decoded later signer = Puppet::SSL::CertificateSigner.new signer.sign(cert.content, key) cert end let(:external_data) { { 'string' => 'a', 'integer' => 1, 'boolean' => true, 'hash' => { 'one' => 'two' }, 'array' => ['b', 2, {}] } } def allow_external_trusted_data(certname, data) command = 'generate_data.sh' Puppet[:trusted_external_command] = command # The expand_path bit is necessary b/c :trusted_external_command is a # file_or_directory setting, and file_or_directory settings automatically # expand the given path. allow(Puppet::Util::Execution).to receive(:execute).with([File.expand_path(command), certname], anything).and_return(JSON.dump(data)) end it "defaults external to an empty hash" do trusted = Puppet::Context::TrustedInformation.new(false, 'ignored', nil) expect(trusted.external).to eq({}) end context "when remote" do it "has no cert information when it isn't authenticated" do trusted = Puppet::Context::TrustedInformation.remote(false, 'ignored', nil) expect(trusted.authenticated).to eq(false) expect(trusted.certname).to be_nil expect(trusted.extensions).to eq({}) end it "is remote and has certificate information when it is authenticated" do trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', cert) expect(trusted.authenticated).to eq('remote') expect(trusted.certname).to eq('cert name') expect(trusted.extensions).to eq({ '1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info', '1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info', }) expect(trusted.hostname).to eq('cert name') expect(trusted.domain).to be_nil end it "is remote but lacks certificate information when it is authenticated" do expect(Puppet).to receive(:info).once.with("TrustedInformation expected a certificate, but none was given.") trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', nil) expect(trusted.authenticated).to eq('remote') expect(trusted.certname).to eq('cert name') expect(trusted.extensions).to eq({}) end it 'contains external trusted data' do allow_external_trusted_data('cert name', external_data) trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', nil) expect(trusted.external).to eq(external_data) end it 'does not run the trusted external command when creating a trusted context' do Puppet[:trusted_external_command] = '/usr/bin/generate_data.sh' expect(Puppet::Util::Execution).to receive(:execute).never Puppet::Context::TrustedInformation.remote(true, 'cert name', cert) end it 'only runs the trusted external command the first time it is invoked' do command = 'generate_data.sh' Puppet[:trusted_external_command] = command # See allow_external_trusted_data to understand why expand_path is necessary expect(Puppet::Util::Execution).to receive(:execute).with([File.expand_path(command), 'cert name'], anything).and_return(JSON.dump(external_data)).once trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', cert) trusted.external trusted.external end end context "when local" do it "is authenticated local with the nodes clientcert" do node = Puppet::Node.new('testing', :parameters => { 'clientcert' => 'cert name' }) trusted = Puppet::Context::TrustedInformation.local(node) expect(trusted.authenticated).to eq('local') expect(trusted.certname).to eq('cert name') expect(trusted.extensions).to eq({}) expect(trusted.hostname).to eq('cert name') expect(trusted.domain).to be_nil end it "is authenticated local with no clientcert when there is no node" do trusted = Puppet::Context::TrustedInformation.local(nil) expect(trusted.authenticated).to eq('local') expect(trusted.certname).to be_nil expect(trusted.extensions).to eq({}) expect(trusted.hostname).to be_nil expect(trusted.domain).to be_nil end it 'contains external trusted data' do allow_external_trusted_data('cert name', external_data) trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', nil) expect(trusted.external).to eq(external_data) end end it "converts itself to a hash" do trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', cert) expect(trusted.to_h).to eq({ 'authenticated' => 'remote', 'certname' => 'cert name', 'extensions' => { '1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info', '1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info', }, 'hostname' => 'cert name', 'domain' => nil, 'external' => {}, }) end it "extracts domain and hostname from certname" do trusted = Puppet::Context::TrustedInformation.remote(true, 'hostname.domain.long', cert) expect(trusted.to_h).to eq({ 'authenticated' => 'remote', 'certname' => 'hostname.domain.long', 'extensions' => { '1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info', '1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info', }, 'hostname' => 'hostname', 'domain' => 'domain.long', 'external' => {}, }) end it "freezes the hash" do trusted = Puppet::Context::TrustedInformation.remote(true, 'cert name', cert) expect(trusted.to_h).to be_deeply_frozen end matcher :be_deeply_frozen do match do |actual| unfrozen_items(actual).empty? end failure_message do |actual| "expected all items to be frozen but <#{unfrozen_items(actual).join(', ')}> was not" end define_method :unfrozen_items do |actual| unfrozen = [] stack = [actual] while item = stack.pop if !item.frozen? unfrozen.push(item) end case item when Hash stack.concat(item.keys) stack.concat(item.values) when Array stack.concat(item) end end unfrozen end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/external_client_spec.rb
spec/unit/http/external_client_spec.rb
require 'spec_helper' require 'puppet/http' # Simple "external" client to make get & post requests. This is used # to test the old HTTP API, such as requiring use_ssl and basic_auth # to be passed as options. class Puppet::HTTP::TestExternal def initialize(host, port, options = {}) @host = host @port = port @options = options @factory = Puppet::HTTP::Factory.new end def get(path, headers = {}, options = {}) request = Net::HTTP::Get.new(path, headers) do_request(request, options) end def post(path, data, headers = nil, options = {}) request = Net::HTTP::Post.new(path, headers) do_request(request, options) end def do_request(request, options) if options[:basic_auth] request.basic_auth(options[:basic_auth][:user], options[:basic_auth][:password]) end site = Puppet::HTTP::Site.new(@options[:use_ssl] ? 'https' : 'http', @host, @port) http = @factory.create_connection(site) http.start begin http.request(request) ensure http.finish end end end describe Puppet::HTTP::ExternalClient do let(:uri) { URI.parse('https://www.example.com') } let(:http_client_class) { Puppet::HTTP::TestExternal } let(:client) { described_class.new(http_client_class) } let(:credentials) { ['user', 'pass'] } context "for GET requests" do it "stringifies keys and encodes values in the query" do stub_request(:get, uri).with(query: "foo=bar%3Dbaz") client.get(uri, params: {:foo => "bar=baz"}) end it "fails if a user passes in an invalid param type" do environment = Puppet::Node::Environment.create(:testing, []) expect{client.get(uri, params: {environment: environment})}.to raise_error(Puppet::HTTP::SerializationError, /HTTP REST queries cannot handle values of type/) end it "returns the response" do stub_request(:get, uri) response = client.get(uri) expect(response).to be_a(Puppet::HTTP::Response) expect(response).to be_success expect(response.code).to eq(200) end it "returns the entire response body" do stub_request(:get, uri).to_return(body: "abc") expect(client.get(uri).body).to eq("abc") end it "streams the response body when a block is given" do stub_request(:get, uri).to_return(body: "abc") io = StringIO.new client.get(uri) do |response| response.read_body do |data| io.write(data) end end expect(io.string).to eq("abc") end context 'when connecting' do it 'accepts an ssl context' do stub_request(:get, uri).to_return(body: "abc") other_context = Puppet::SSL::SSLContext.new client.get(uri, options: {ssl_context: other_context}) end it 'accepts include_system_store' do stub_request(:get, uri).to_return(body: "abc") client.get(uri, options: {include_system_store: true}) end end end context "for POST requests" do it "stringifies keys and encodes values in the query" do stub_request(:post, "https://www.example.com").with(query: "foo=bar%3Dbaz") client.post(uri, "", params: {:foo => "bar=baz"}, headers: {'Content-Type' => 'text/plain'}) end it "returns the response" do stub_request(:post, uri) response = client.post(uri, "", headers: {'Content-Type' => 'text/plain'}) expect(response).to be_a(Puppet::HTTP::Response) expect(response).to be_success expect(response.code).to eq(200) end it "sets content-type for the body" do stub_request(:post, uri).with(headers: {"Content-Type" => "text/plain"}) client.post(uri, "hello", headers: {'Content-Type' => 'text/plain'}) end it "streams the response body when a block is given" do stub_request(:post, uri).to_return(body: "abc") io = StringIO.new client.post(uri, "", headers: {'Content-Type' => 'text/plain'}) do |response| response.read_body do |data| io.write(data) end end expect(io.string).to eq("abc") end it 'raises an ArgumentError if `body` is missing' do expect { client.post(uri, nil, headers: {'Content-Type' => 'text/plain'}) }.to raise_error(ArgumentError, /'post' requires a string 'body' argument/) end context 'when connecting' do it 'accepts an ssl context' do stub_request(:post, uri) other_context = Puppet::SSL::SSLContext.new client.post(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {ssl_context: other_context}) end it 'accepts include_system_store' do stub_request(:post, uri) client.post(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {include_system_store: true}) end end end context "Basic Auth" do it "submits credentials for GET requests" do stub_request(:get, uri).with(basic_auth: credentials) client.get(uri, options: {basic_auth: {user: 'user', password: 'pass'}}) end it "submits credentials for POST requests" do stub_request(:post, uri).with(basic_auth: credentials) client.post(uri, "", options: {content_type: 'text/plain', basic_auth: {user: 'user', password: 'pass'}}) end it "returns response containing access denied" do stub_request(:get, uri).with(basic_auth: credentials).to_return(status: [403, "Ye Shall Not Pass"]) response = client.get(uri, options: { basic_auth: {user: 'user', password: 'pass'}}) expect(response.code).to eq(403) expect(response.reason).to eq("Ye Shall Not Pass") expect(response).to_not be_success end it 'includes basic auth if user is nil' do stub_request(:get, uri).with do |req| expect(req.headers).to include('Authorization') end client.get(uri, options: {basic_auth: {user: nil, password: 'pass'}}) end it 'includes basic auth if password is nil' do stub_request(:get, uri).with do |req| expect(req.headers).to include('Authorization') end client.get(uri, options: {basic_auth: {user: 'user', password: nil}}) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/response_spec.rb
spec/unit/http/response_spec.rb
require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::Response do let(:uri) { URI.parse('https://www.example.com') } let(:client) { Puppet::HTTP::Client.new } it "returns the request URL" do stub_request(:get, uri) response = client.get(uri) expect(response.url).to eq(uri) end it "returns the HTTP code" do stub_request(:get, uri) response = client.get(uri) expect(response.code).to eq(200) end it "returns the HTTP reason string" do stub_request(:get, uri).to_return(status: [418, "I'm a teapot"]) response = client.get(uri) expect(response.reason).to eq("I'm a teapot") end it "returns the response body" do stub_request(:get, uri).to_return(status: 200, body: "I'm the body") response = client.get(uri) expect(response.body).to eq("I'm the body") end it "streams the response body" do stub_request(:get, uri).to_return(status: 200, body: "I'm the streaming body") content = StringIO.new client.get(uri) do |response| response.read_body do |data| content << data end end expect(content.string).to eq("I'm the streaming body") end it "raises if a block isn't given when streaming" do stub_request(:get, uri).to_return(status: 200, body: "") expect { client.get(uri) do |response| response.read_body end }.to raise_error(Puppet::HTTP::HTTPError, %r{Request to https://www.example.com failed after .* seconds: A block is required}) end it "returns success for all 2xx codes" do stub_request(:get, uri).to_return(status: 202) expect(client.get(uri)).to be_success end it "returns a header value" do stub_request(:get, uri).to_return(status: 200, headers: { 'Content-Encoding' => 'gzip' }) expect(client.get(uri)['Content-Encoding']).to eq('gzip') end it "enumerates headers" do stub_request(:get, uri).to_return(status: 200, headers: { 'Content-Encoding' => 'gzip' }) expect(client.get(uri).each_header.to_a).to eq([['content-encoding', 'gzip']]) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/site_spec.rb
spec/unit/http/site_spec.rb
require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::Site do let(:scheme) { 'https' } let(:host) { 'rubygems.org' } let(:port) { 443 } def create_site(scheme, host, port) described_class.new(scheme, host, port) end it 'accepts scheme, host, and port' do site = create_site(scheme, host, port) expect(site.scheme).to eq(scheme) expect(site.host).to eq(host) expect(site.port).to eq(port) end it 'generates an external URI string' do site = create_site(scheme, host, port) expect(site.addr).to eq("https://rubygems.org:443") end it 'considers sites to be different when the scheme is different' do https_site = create_site('https', host, port) http_site = create_site('http', host, port) expect(https_site).to_not eq(http_site) end it 'considers sites to be different when the host is different' do rubygems_site = create_site(scheme, 'rubygems.org', port) github_site = create_site(scheme, 'github.com', port) expect(rubygems_site).to_not eq(github_site) end it 'considers sites to be different when the port is different' do site_443 = create_site(scheme, host, 443) site_80 = create_site(scheme, host, 80) expect(site_443).to_not eq(site_80) end it 'compares values when determining equality' do site = create_site(scheme, host, port) sites = {} sites[site] = site another_site = create_site(scheme, host, port) expect(sites.include?(another_site)).to be_truthy end it 'computes the same hash code for equivalent objects' do site = create_site(scheme, host, port) same_site = create_site(scheme, host, port) expect(site.hash).to eq(same_site.hash) end it 'uses ssl with https' do site = create_site('https', host, port) expect(site).to be_use_ssl end it 'does not use ssl with http' do site = create_site('http', host, port) expect(site).to_not be_use_ssl end it 'moves to a new URI location' do site = create_site('http', 'host1', 80) uri = URI.parse('https://host2:443/some/where/else') new_site = site.move_to(uri) expect(new_site.scheme).to eq('https') expect(new_site.host).to eq('host2') expect(new_site.port).to eq(443) end it 'creates a site from a URI' do site = create_site('https', 'rubygems.org', 443) uri = URI.parse('https://rubygems.org/gems/puppet/') expect(described_class.from_uri(uri)).to eq(site) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/client_spec.rb
spec/unit/http/client_spec.rb
require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::Client do let(:uri) { URI.parse('https://www.example.com') } let(:puppet_context) { Puppet::SSL::SSLContext.new } let(:system_context) { Puppet::SSL::SSLContext.new } let(:client) { described_class.new(ssl_context: puppet_context, system_ssl_context: system_context) } let(:credentials) { ['user', 'pass'] } it 'creates unique sessions' do expect(client.create_session).to_not eq(client.create_session) end context "when connecting" do it 'connects to HTTP URLs' do uri = URI.parse('http://www.example.com') client.connect(uri) do |http| expect(http.address).to eq('www.example.com') expect(http.port).to eq(80) expect(http).to_not be_use_ssl end end it 'connects to HTTPS URLs' do client.connect(uri) do |http| expect(http.address).to eq('www.example.com') expect(http.port).to eq(443) expect(http).to be_use_ssl end end it 'raises ConnectionError if the connection is refused' do allow_any_instance_of(Net::HTTP).to receive(:start).and_raise(Errno::ECONNREFUSED) expect { client.connect(uri) }.to raise_error(Puppet::HTTP::ConnectionError, %r{^Request to https://www.example.com failed after .* seconds: (Connection refused|No connection could be made because the target machine actively refused it)}) end it 'raises ConnectionError if the connect times out' do allow_any_instance_of(Net::HTTP).to receive(:start).and_raise(Net::OpenTimeout) expect { client.connect(uri) }.to raise_error(Puppet::HTTP::ConnectionError, %r{^Request to https://www.example.com timed out connect operation after .* seconds}) end it 'connects using the default ssl context' do expect(client.pool).to receive(:with_connection) do |_, verifier| expect(verifier.ssl_context).to equal(puppet_context) end client.connect(uri) end it 'connects using a specified ssl context' do other_context = Puppet::SSL::SSLContext.new expect(client.pool).to receive(:with_connection) do |_, verifier| expect(verifier.ssl_context).to equal(other_context) end client.connect(uri, options: {ssl_context: other_context}) end it 'connects using the system store' do expect(client.pool).to receive(:with_connection) do |_, verifier| expect(verifier.ssl_context).to equal(system_context) end client.connect(uri, options: {include_system_store: true}) end it 'does not create a verifier for HTTP connections' do expect(client.pool).to receive(:with_connection) do |_, verifier| expect(verifier).to be_nil end client.connect(URI.parse('http://www.example.com')) end it 'raises an HTTPError if both are specified' do expect { client.connect(uri, options: {ssl_context: puppet_context, include_system_store: true}) }.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/) end end context 'after connecting' do def expect_http_error(cause, expected_message) expect { client.connect(uri) do |_| raise cause, 'whoops' end }.to raise_error(Puppet::HTTP::HTTPError, expected_message) end it 're-raises HTTPError' do expect_http_error(Puppet::HTTP::HTTPError, 'whoops') end it 'raises HTTPError if connection is interrupted while reading' do expect_http_error(EOFError, %r{^Request to https://www.example.com interrupted after .* seconds}) end it 'raises HTTPError if connection times out' do expect_http_error(Net::ReadTimeout, %r{^Request to https://www.example.com timed out read operation after .* seconds}) end it 'raises HTTPError if connection fails' do expect_http_error(ArgumentError, %r{^Request to https://www.example.com failed after .* seconds}) end end context "when closing" do it "closes all connections in the pool" do expect(client.pool).to receive(:close) client.close end it 'reloads the default ssl context' do expect(client.pool).to receive(:with_connection) do |_, verifier| expect(verifier.ssl_context).to_not equal(puppet_context) end client.close client.connect(uri) end it 'reloads the default system ssl context' do expect(client.pool).to receive(:with_connection) do |_, verifier| expect(verifier.ssl_context).to_not equal(system_context) end client.close client.connect(uri, options: {include_system_store: true}) end end context "for GET requests" do it "includes default HTTP headers" do stub_request(:get, uri).with do |request| expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./}) expect(request.headers).to_not include('X-Puppet-Profiling') end client.get(uri) end it "stringifies keys and encodes values in the query" do stub_request(:get, uri).with(query: "foo=bar%3Dbaz") client.get(uri, params: {:foo => "bar=baz"}) end it "fails if a user passes in an invalid param type" do environment = Puppet::Node::Environment.create(:testing, []) expect{client.get(uri, params: {environment: environment})}.to raise_error(Puppet::HTTP::SerializationError, /HTTP REST queries cannot handle values of type/) end it "merges custom headers with default ones" do stub_request(:get, uri).with(headers: { 'X-Foo' => 'Bar', 'X-Puppet-Version' => /./, 'User-Agent' => /./ }) client.get(uri, headers: {'X-Foo' => 'Bar'}) end it "returns the response" do stub_request(:get, uri) response = client.get(uri) expect(response).to be_a(Puppet::HTTP::Response) expect(response).to be_success expect(response.code).to eq(200) end it "returns the entire response body" do stub_request(:get, uri).to_return(body: "abc") expect(client.get(uri).body).to eq("abc") end it "streams the response body when a block is given" do stub_request(:get, uri).to_return(body: "abc") io = StringIO.new client.get(uri) do |response| response.read_body do |data| io.write(data) end end expect(io.string).to eq("abc") end context 'when connecting' do it 'uses a specified ssl context' do stub_request(:get, uri).to_return(body: "abc") other_context = Puppet::SSL::SSLContext.new client.get(uri, options: {ssl_context: other_context}) end it 'uses the system store' do stub_request(:get, uri).to_return(body: "abc") client.get(uri, options: {include_system_store: true}) end it 'raises an HTTPError if both are specified' do expect { client.get(uri, options: {ssl_context: puppet_context, include_system_store: true}) }.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/) end end end context "for HEAD requests" do it "includes default HTTP headers" do stub_request(:head, uri).with(headers: {'X-Puppet-Version' => /./, 'User-Agent' => /./}) client.head(uri) end it "stringifies keys and encodes values in the query" do stub_request(:head, uri).with(query: "foo=bar%3Dbaz") client.head(uri, params: {:foo => "bar=baz"}) end it "merges custom headers with default ones" do stub_request(:head, uri).with(headers: { 'X-Foo' => 'Bar', 'X-Puppet-Version' => /./, 'User-Agent' => /./ }) client.head(uri, headers: {'X-Foo' => 'Bar'}) end it "returns the response" do stub_request(:head, uri) response = client.head(uri) expect(response).to be_a(Puppet::HTTP::Response) expect(response).to be_success expect(response.code).to eq(200) end it "returns the entire response body" do stub_request(:head, uri).to_return(body: "abc") expect(client.head(uri).body).to eq("abc") end context 'when connecting' do it 'uses a specified ssl context' do stub_request(:head, uri) other_context = Puppet::SSL::SSLContext.new client.head(uri, options: {ssl_context: other_context}) end it 'uses the system store' do stub_request(:head, uri) client.head(uri, options: {include_system_store: true}) end it 'raises an HTTPError if both are specified' do expect { client.head(uri, options: {ssl_context: puppet_context, include_system_store: true}) }.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/) end end end context "for PUT requests" do it "includes default HTTP headers" do stub_request(:put, uri).with do |request| expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./}) expect(request.headers).to_not include('X-Puppet-Profiling') end client.put(uri, "", headers: {'Content-Type' => 'text/plain'}) end it "stringifies keys and encodes values in the query" do stub_request(:put, "https://www.example.com").with(query: "foo=bar%3Dbaz") client.put(uri, "", params: {:foo => "bar=baz"}, headers: {'Content-Type' => 'text/plain'}) end it "includes custom headers" do stub_request(:put, "https://www.example.com").with(headers: { 'X-Foo' => 'Bar' }) client.put(uri, "", headers: {'X-Foo' => 'Bar', 'Content-Type' => 'text/plain'}) end it "returns the response" do stub_request(:put, uri) response = client.put(uri, "", headers: {'Content-Type' => 'text/plain'}) expect(response).to be_a(Puppet::HTTP::Response) expect(response).to be_success expect(response.code).to eq(200) end it "sets content-length and content-type for the body" do stub_request(:put, uri).with(headers: {"Content-Length" => "5", "Content-Type" => "text/plain"}) client.put(uri, "hello", headers: {'Content-Type' => 'text/plain'}) end it 'raises an ArgumentError if `body` is missing' do expect { client.put(uri, nil, headers: {'Content-Type' => 'text/plain'}) }.to raise_error(ArgumentError, /'put' requires a string 'body' argument/) end it 'raises an ArgumentError if `content_type` is missing from the headers hash' do expect { client.put(uri, '') }.to raise_error(ArgumentError, /'put' requires a 'content-type' header/) end context 'when connecting' do it 'uses a specified ssl context' do stub_request(:put, uri) other_context = Puppet::SSL::SSLContext.new client.put(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {ssl_context: other_context}) end it 'uses the system store' do stub_request(:put, uri) client.put(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {include_system_store: true}) end it 'raises an HTTPError if both are specified' do expect { client.put(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {ssl_context: puppet_context, include_system_store: true}) }.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/) end end end context "for POST requests" do it "includes default HTTP headers" do stub_request(:post, uri).with(headers: {'X-Puppet-Version' => /./, 'User-Agent' => /./}) client.post(uri, "", headers: {'Content-Type' => 'text/plain'}) end it "stringifies keys and encodes values in the query" do stub_request(:post, "https://www.example.com").with(query: "foo=bar%3Dbaz") client.post(uri, "", params: {:foo => "bar=baz"}, headers: {'Content-Type' => 'text/plain'}) end it "includes custom headers" do stub_request(:post, "https://www.example.com").with(headers: { 'X-Foo' => 'Bar' }) client.post(uri, "", headers: {'X-Foo' => 'Bar', 'Content-Type' => 'text/plain'}) end it "returns the response" do stub_request(:post, uri) response = client.post(uri, "", headers: {'Content-Type' => 'text/plain'}) expect(response).to be_a(Puppet::HTTP::Response) expect(response).to be_success expect(response.code).to eq(200) end it "sets content-length and content-type for the body" do stub_request(:post, uri).with(headers: {"Content-Length" => "5", "Content-Type" => "text/plain"}) client.post(uri, "hello", headers: {'Content-Type' => 'text/plain'}) end it "streams the response body when a block is given" do stub_request(:post, uri).to_return(body: "abc") io = StringIO.new client.post(uri, "", headers: {'Content-Type' => 'text/plain'}) do |response| response.read_body do |data| io.write(data) end end expect(io.string).to eq("abc") end it 'raises an ArgumentError if `body` is missing' do expect { client.post(uri, nil, headers: {'Content-Type' => 'text/plain'}) }.to raise_error(ArgumentError, /'post' requires a string 'body' argument/) end it 'raises an ArgumentError if `content_type` is missing from the headers hash' do expect { client.post(uri, "") }.to raise_error(ArgumentError, /'post' requires a 'content-type' header/) end context 'when connecting' do it 'uses a specified ssl context' do stub_request(:post, uri) other_context = Puppet::SSL::SSLContext.new client.post(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {body: "", ssl_context: other_context}) end it 'uses the system store' do stub_request(:post, uri) client.post(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {include_system_store: true}) end it 'raises an HTTPError if both are specified' do expect { client.post(uri, "", headers: {'Content-Type' => 'text/plain'}, options: {ssl_context: puppet_context, include_system_store: true}) }.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/) end end end context "for DELETE requests" do it "includes default HTTP headers" do stub_request(:delete, uri).with(headers: {'X-Puppet-Version' => /./, 'User-Agent' => /./}) client.delete(uri) end it "merges custom headers with default ones" do stub_request(:delete, uri).with(headers: { 'X-Foo' => 'Bar', 'X-Puppet-Version' => /./, 'User-Agent' => /./ }) client.delete(uri, headers: {'X-Foo' => 'Bar'}) end it "stringifies keys and encodes values in the query" do stub_request(:delete, "https://www.example.com").with(query: "foo=bar%3Dbaz") client.delete(uri, params: {:foo => "bar=baz"}) end it "returns the response" do stub_request(:delete, uri) response = client.delete(uri) expect(response).to be_a(Puppet::HTTP::Response) expect(response).to be_success expect(response.code).to eq(200) end it "returns the entire response body" do stub_request(:delete, uri).to_return(body: "abc") expect(client.delete(uri).body).to eq("abc") end context 'when connecting' do it 'uses a specified ssl context' do stub_request(:delete, uri) other_context = Puppet::SSL::SSLContext.new client.delete(uri, options: {ssl_context: other_context}) end it 'uses the system store' do stub_request(:delete, uri) client.delete(uri, options: {include_system_store: true}) end it 'raises an HTTPError if both are specified' do expect { client.delete(uri, options: {ssl_context: puppet_context, include_system_store: true}) }.to raise_error(Puppet::HTTP::HTTPError, /The ssl_context and include_system_store parameters are mutually exclusive/) end end end context "Basic Auth" do it "submits credentials for GET requests" do stub_request(:get, uri).with(basic_auth: credentials) client.get(uri, options: {basic_auth: {user: 'user', password: 'pass'}}) end it "submits credentials for PUT requests" do stub_request(:put, uri).with(basic_auth: credentials) client.put(uri, "hello", headers: {'Content-Type' => 'text/plain'}, options: {basic_auth: {user: 'user', password: 'pass'}}) end it "returns response containing access denied" do stub_request(:get, uri).with(basic_auth: credentials).to_return(status: [403, "Ye Shall Not Pass"]) response = client.get(uri, options: {basic_auth: {user: 'user', password: 'pass'}}) expect(response.code).to eq(403) expect(response.reason).to eq("Ye Shall Not Pass") expect(response).to_not be_success end it 'includes basic auth if user is nil' do stub_request(:get, uri).with do |req| expect(req.headers).to include('Authorization') end client.get(uri, options: {basic_auth: {user: nil, password: 'pass'}}) end it 'includes basic auth if password is nil' do stub_request(:get, uri).with do |req| expect(req.headers).to include('Authorization') end client.get(uri, options: {basic_auth: {user: 'user', password: nil}}) end it 'observes userinfo in the URL' do stub_request(:get, uri).with(basic_auth: credentials) client.get(URI("https://user:pass@www.example.com")) end it 'prefers explicit basic_auth credentials' do uri = URI("https://ignored_user:ignored_pass@www.example.com") stub_request(:get, "https://www.example.com").with(basic_auth: credentials) client.get(uri, options: {basic_auth: {user: 'user', password: 'pass'}}) end end context "when redirecting" do let(:start_url) { URI("https://www.example.com:8140/foo") } let(:bar_url) { "https://www.example.com:8140/bar" } let(:baz_url) { "https://www.example.com:8140/baz" } let(:other_host) { "https://other.example.com:8140/qux" } def redirect_to(status: 302, url:) { status: status, headers: { 'Location' => url }, body: "Redirected to #{url}" } end it "preserves GET method" do stub_request(:get, start_url).to_return(redirect_to(url: bar_url)) stub_request(:get, bar_url).to_return(status: 200) response = client.get(start_url) expect(response).to be_success end it "preserves PUT method" do stub_request(:put, start_url).to_return(redirect_to(url: bar_url)) stub_request(:put, bar_url).to_return(status: 200) response = client.put(start_url, "", headers: {'Content-Type' => 'text/plain'}) expect(response).to be_success end it "updates the Host header from the Location host and port" do stub_request(:get, start_url).with(headers: { 'Host' => 'www.example.com:8140' }) .to_return(redirect_to(url: other_host)) stub_request(:get, other_host).with(headers: { 'Host' => 'other.example.com:8140' }) .to_return(status: 200) response = client.get(start_url) expect(response).to be_success end it "omits the default HTTPS port from the Host header" do stub_request(:get, start_url).with(headers: { 'Host' => 'www.example.com:8140' }) .to_return(redirect_to(url: "https://other.example.com/qux")) stub_request(:get, "https://other.example.com/qux").with(headers: { 'Host' => 'other.example.com' }) .to_return(status: 200) response = client.get(start_url) expect(response).to be_success end it "omits the default HTTP port from the Host header" do stub_request(:get, start_url).with(headers: { 'Host' => 'www.example.com:8140' }) .to_return(redirect_to(url: "http://other.example.com/qux")) stub_request(:get, "http://other.example.com/qux").with(headers: { 'Host' => 'other.example.com' }) .to_return(status: 200) response = client.get(start_url) expect(response).to be_success end it "applies query parameters from the location header" do query = { 'redirected' => false } stub_request(:get, start_url).with(query: query).to_return(redirect_to(url: "#{bar_url}?redirected=true")) stub_request(:get, bar_url).with(query: {'redirected' => 'true'}).to_return(status: 200) response = client.get(start_url, params: query) expect(response).to be_success end it "preserves custom and default headers when redirecting" do headers = { 'X-Foo' => 'Bar', 'X-Puppet-Version' => Puppet.version } stub_request(:get, start_url).with(headers: headers).to_return(redirect_to(url: bar_url)) stub_request(:get, bar_url).with(headers: headers).to_return(status: 200) response = client.get(start_url, headers: headers) expect(response).to be_success end it "does not preserve basic authorization when redirecting to different hosts" do stub_request(:get, start_url).with(basic_auth: credentials).to_return(redirect_to(url: other_host)) stub_request(:get, other_host).to_return(status: 200) client.get(start_url, options: {basic_auth: {user: 'user', password: 'pass'}}) expect(a_request(:get, other_host). with{ |req| !req.headers.key?('Authorization')}).to have_been_made end it "does preserve basic authorization when redirecting to the same hosts" do stub_request(:get, start_url).with(basic_auth: credentials).to_return(redirect_to(url: bar_url)) stub_request(:get, bar_url).with(basic_auth: credentials).to_return(status: 200) client.get(start_url, options: {basic_auth: {user: 'user', password: 'pass'}}) expect(a_request(:get, bar_url). with{ |req| req.headers.key?('Authorization')}).to have_been_made end it "does not preserve cookie header when redirecting to different hosts" do headers = { 'Cookie' => 'TEST_COOKIE'} stub_request(:get, start_url).with(headers: headers).to_return(redirect_to(url: other_host)) stub_request(:get, other_host).to_return(status: 200) client.get(start_url, headers: headers) expect(a_request(:get, other_host). with{ |req| !req.headers.key?('Cookie')}).to have_been_made end it "does preserve cookie header when redirecting to the same hosts" do headers = { 'Cookie' => 'TEST_COOKIE'} stub_request(:get, start_url).with(headers: headers).to_return(redirect_to(url: bar_url)) stub_request(:get, bar_url).with(headers: headers).to_return(status: 200) client.get(start_url, headers: headers) expect(a_request(:get, bar_url). with{ |req| req.headers.key?('Cookie')}).to have_been_made end it "does preserves cookie header and basic authentication when Puppet[:location_trusted] is true redirecting to different hosts" do headers = { 'cookie' => 'TEST_COOKIE'} Puppet[:location_trusted] = true stub_request(:get, start_url).with(headers: headers, basic_auth: credentials).to_return(redirect_to(url: other_host)) stub_request(:get, other_host).with(headers: headers, basic_auth: credentials).to_return(status: 200) client.get(start_url, headers: headers, options: {basic_auth: {user: 'user', password: 'pass'}}) expect(a_request(:get, other_host). with{ |req| req.headers.key?('Authorization') && req.headers.key?('Cookie')}).to have_been_made end it "treats hosts as case-insensitive" do start_url = URI("https://www.EXAmple.com:8140/Start") bar_url = "https://www.example.com:8140/bar" stub_request(:get, start_url).with(basic_auth: credentials).to_return(redirect_to(url: bar_url)) stub_request(:get, bar_url).with(basic_auth: credentials).to_return(status: 200) client.get(start_url, options: {basic_auth: {user: 'user', password: 'pass'}}) expect(a_request(:get, bar_url). with{ |req| req.headers.key?('Authorization')}).to have_been_made end it "redirects given a relative location" do relative_url = "/people.html" stub_request(:get, start_url).to_return(redirect_to(url: relative_url)) stub_request(:get, "https://www.example.com:8140/people.html").to_return(status: 200) response = client.get(start_url) expect(response).to be_success end it "applies query parameters from the location header" do relative_url = "/people.html" query = { 'redirected' => false } stub_request(:get, start_url).with(query: query).to_return(redirect_to(url: "#{relative_url}?redirected=true")) stub_request(:get, "https://www.example.com:8140/people.html").with(query: {'redirected' => 'true'}).to_return(status: 200) response = client.get(start_url, params: query) expect(response).to be_success end it "removes dot segments from a relative location" do # from https://tools.ietf.org/html/rfc3986#section-5.4.2 base_url = URI("http://a/b/c/d;p?q") relative_url = "../../../../g" stub_request(:get, base_url).to_return(redirect_to(url: relative_url)) stub_request(:get, "http://a/g").to_return(status: 200) response = client.get(base_url) expect(response).to be_success end it "preserves request body for each request" do data = 'some data' stub_request(:put, start_url).with(body: data).to_return(redirect_to(url: bar_url)) stub_request(:put, bar_url).with(body: data).to_return(status: 200) response = client.put(start_url, data, headers: {'Content-Type' => 'text/plain'}) expect(response).to be_success end it "returns the body from the final response" do stub_request(:get, start_url).to_return(redirect_to(url: bar_url)) stub_request(:get, bar_url).to_return(status: 200, body: 'followed') response = client.get(start_url) expect(response.body).to eq('followed') end [301, 307].each do |code| it "also redirects on #{code}" do stub_request(:get, start_url).to_return(redirect_to(status: code, url: bar_url)) stub_request(:get, bar_url).to_return(status: 200) response = client.get(start_url) expect(response).to be_success end end [303, 308].each do |code| it "returns an error on #{code}" do stub_request(:get, start_url).to_return(redirect_to(status: code, url: bar_url)) response = client.get(start_url) expect(response.code).to eq(code) expect(response).to_not be_success end end it "raises an error if the Location header is missing" do stub_request(:get, start_url).to_return(status: 302) expect { client.get(start_url) }.to raise_error(Puppet::HTTP::ProtocolError, "Location response header is missing") end it "raises an error if the Location header is invalid" do stub_request(:get, start_url).to_return(redirect_to(status: 302, url: 'http://foo"bar')) expect { client.get(start_url) }.to raise_error(Puppet::HTTP::ProtocolError, /Location URI is invalid/) end it "raises an error if limit is 0 and we're asked to follow" do stub_request(:get, start_url).to_return(redirect_to(url: bar_url)) client = described_class.new(redirect_limit: 0) expect { client.get(start_url) }.to raise_error(Puppet::HTTP::TooManyRedirects, %r{Too many HTTP redirections for https://www.example.com:8140}) end it "raises an error if asked to follow redirects more times than the limit" do stub_request(:get, start_url).to_return(redirect_to(url: bar_url)) stub_request(:get, bar_url).to_return(redirect_to(url: baz_url)) client = described_class.new(redirect_limit: 1) expect { client.get(start_url) }.to raise_error(Puppet::HTTP::TooManyRedirects, %r{Too many HTTP redirections for https://www.example.com:8140}) end it "follows multiple redirects if equal to or less than the redirect limit" do stub_request(:get, start_url).to_return(redirect_to(url: bar_url)) stub_request(:get, bar_url).to_return(redirect_to(url: baz_url)) stub_request(:get, baz_url).to_return(status: 200) client = described_class.new(redirect_limit: 2) response = client.get(start_url) expect(response).to be_success end it "redirects to a different host" do stub_request(:get, start_url).to_return(redirect_to(url: other_host)) stub_request(:get, other_host).to_return(status: 200) response = client.get(start_url) expect(response).to be_success end it "redirects from http to https" do http = URI("http://example.com/foo") https = URI("https://example.com/bar") stub_request(:get, http).to_return(redirect_to(url: https)) stub_request(:get, https).to_return(status: 200) response = client.get(http) expect(response).to be_success end it "redirects from https to http" do http = URI("http://example.com/foo") https = URI("https://example.com/bar") stub_request(:get, https).to_return(redirect_to(url: http)) stub_request(:get, http).to_return(status: 200) response = client.get(https) expect(response).to be_success end it "does not preserve accept-encoding header when redirecting" do headers = { 'Accept-Encoding' => 'unwanted-encoding'} stub_request(:get, start_url).with(headers: headers).to_return(redirect_to(url: other_host)) stub_request(:get, other_host).to_return(status: 200) client.get(start_url, headers: headers) expect(a_request(:get, other_host). with{ |req| req.headers['Accept-Encoding'] != 'unwanted-encoding' }).to have_been_made end end context "when response indicates an overloaded server" do def retry_after(datetime) stub_request(:get, uri) .to_return(status: [503, 'Service Unavailable'], headers: {'Retry-After' => datetime}).then .to_return(status: 200) end it "returns a 503 response if Retry-After is not set" do stub_request(:get, uri).to_return(status: [503, 'Service Unavailable']) expect(client.get(uri).code).to eq(503) end it "raises if Retry-After is not convertible to an Integer or RFC 2822 Date" do stub_request(:get, uri).to_return(status: [503, 'Service Unavailable'], headers: {'Retry-After' => 'foo'}) expect { client.get(uri) }.to raise_error(Puppet::HTTP::ProtocolError, /Failed to parse Retry-After header 'foo' as an integer or RFC 2822 date/) end it "should close the connection before sleeping" do retry_after('42') site = Puppet::HTTP::Site.from_uri(uri) http1 = Net::HTTP.new(site.host, site.port) http1.use_ssl = true allow(http1).to receive(:started?).and_return(true) http2 = Net::HTTP.new(site.host, site.port) http2.use_ssl = true allow(http2).to receive(:started?).and_return(true) pool = Puppet::HTTP::Pool.new(15) client = Puppet::HTTP::Client.new(pool: pool) # The "with_connection" method is required to yield started connections allow(pool).to receive(:with_connection).and_yield(http1).and_yield(http2) expect(http1).to receive(:finish).ordered expect(::Kernel).to receive(:sleep).with(42).ordered client.get(uri) end it "should sleep and retry if Retry-After is an Integer" do retry_after('42') expect(::Kernel).to receive(:sleep).with(42) client.get(uri) end it "should sleep and retry if Retry-After is an RFC 2822 Date" do retry_after('Wed, 13 Apr 2005 15:18:05 GMT') now = DateTime.new(2005, 4, 13, 8, 17, 5, '-07:00') allow(DateTime).to receive(:now).and_return(now) expect(::Kernel).to receive(:sleep).with(60) client.get(uri) end it "should sleep for no more than the Puppet runinterval" do retry_after('60') Puppet[:runinterval] = 30 expect(::Kernel).to receive(:sleep).with(30) client.get(uri) end it "should sleep for 0 seconds if the RFC 2822 date has past" do retry_after('Wed, 13 Apr 2005 15:18:05 GMT') expect(::Kernel).to receive(:sleep).with(0) client.get(uri) end end context "persistent connections" do before :each do stub_request(:get, uri) end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/pool_entry_spec.rb
spec/unit/http/pool_entry_spec.rb
require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::PoolEntry do let(:connection) { double('connection') } let(:verifier) { double('verifier') } def create_session(connection, expiration_time = nil) expiration_time ||= Time.now + 60 * 60 described_class.new(connection, verifier, expiration_time) end it 'provides access to its connection' do session = create_session(connection) expect(session.connection).to eq(connection) end it 'provides access to its verifier' do session = create_session(connection) expect(session.verifier).to eq(verifier) end it 'expires a connection whose expiration time is in the past' do now = Time.now past = now - 1 session = create_session(connection, past) expect(session.expired?(now)).to be_truthy end it 'expires a connection whose expiration time is now' do now = Time.now session = create_session(connection, now) expect(session.expired?(now)).to be_truthy end it 'does not expire a connection whose expiration time is in the future' do now = Time.now future = now + 1 session = create_session(connection, future) expect(session.expired?(now)).to be_falsey end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/proxy_spec.rb
spec/unit/http/proxy_spec.rb
require 'uri' require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::Proxy do before(:all) do ENV['http_proxy'] = nil ENV['HTTP_PROXY'] = nil end host, port, user, password = 'some.host', 1234, 'user1', 'pAssw0rd' def expects_direct_connection_to(http, www) expect(http.address).to eq(www.host) expect(http.port).to eq(www.port) expect(http.proxy_address).to be_nil expect(http.proxy_port).to be_nil expect(http.proxy_user).to be_nil expect(http.proxy_pass).to be_nil end def expects_proxy_connection_via(http, www, host, port, user, password) expect(http.address).to eq(www.host) expect(http.port).to eq(www.port) expect(http.proxy_address).to eq(host) expect(http.proxy_port).to eq(port) expect(http.proxy_user).to eq(user) expect(http.proxy_pass).to eq(password) end describe '.proxy' do let(:www) { URI::HTTP.build(host: 'www.example.com', port: 80) } it 'uses a proxy' do Puppet[:http_proxy_host] = host Puppet[:http_proxy_port] = port Puppet[:http_proxy_user] = user Puppet[:http_proxy_password] = password http = subject.proxy(www) expects_proxy_connection_via(http, www, host, port, user, password) end it 'connects directly to the server' do http = subject.proxy(www) expects_direct_connection_to(http, www) end it 'connects directly to the server when HTTP_PROXY environment variable is set, but server matches no_proxy setting' do Puppet[:http_proxy_host] = host Puppet[:http_proxy_port] = port Puppet[:no_proxy] = www.host Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do http = subject.proxy(www) expects_direct_connection_to(http, www) end end context 'when setting no_proxy' do before :each do Puppet[:http_proxy_host] = host Puppet[:http_proxy_port] = port end it 'connects directly to the server when HTTP_PROXY environment variable is set, but server matches no_proxy setting' do Puppet[:no_proxy] = www.host Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do http = subject.proxy(www) expects_direct_connection_to(http, www) end end it 'connects directly to the server when no_proxy matches wildcard domain' do Puppet[:no_proxy] = '*.example.com' http = subject.proxy(www) expects_direct_connection_to(http, www) end it 'connects directly to the server when no_proxy matches dotted domain' do Puppet[:no_proxy] = '.example.com' http = subject.proxy(www) expects_direct_connection_to(http, www) end it 'connects directly to the server when no_proxy matches a domain suffix like ruby does' do Puppet[:no_proxy] = 'example.com' http = subject.proxy(www) expects_direct_connection_to(http, www) end it 'connects directly to the server when no_proxy matches a partial suffix like ruby does' do Puppet[:no_proxy] = 'ample.com' http = subject.proxy(www) expects_direct_connection_to(http, www) end it 'connects directly to the server when it is a subdomain of no_proxy' do Puppet[:no_proxy] = '*.com' http = subject.proxy(www) expects_direct_connection_to(http, www) end it 'connects directly to the server when no_proxy is *' do Puppet[:no_proxy] = '*' http = subject.proxy(www) expects_direct_connection_to(http, www) end end end describe ".http_proxy_env" do it "should return nil if no environment variables" do expect(subject.http_proxy_env).to eq(nil) end it "should return a URI::HTTP object if http_proxy env variable is set" do Puppet::Util.withenv('HTTP_PROXY' => host) do expect(subject.http_proxy_env).to eq(URI.parse(host)) end end it "should return a URI::HTTP object if HTTP_PROXY env variable is set" do Puppet::Util.withenv('HTTP_PROXY' => host) do expect(subject.http_proxy_env).to eq(URI.parse(host)) end end it "should return a URI::HTTP object with .host and .port if URI is given" do Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do expect(subject.http_proxy_env).to eq(URI.parse("http://#{host}:#{port}")) end end it "should return nil if proxy variable is malformed" do Puppet::Util.withenv('HTTP_PROXY' => 'this is not a valid URI') do expect(subject.http_proxy_env).to eq(nil) end end end describe ".http_proxy_host" do it "should return nil if no proxy host in config or env" do expect(subject.http_proxy_host).to eq(nil) end it "should return a proxy host if set in config" do Puppet.settings[:http_proxy_host] = host expect(subject.http_proxy_host).to eq(host) end it "should return nil if set to `none` in config" do Puppet.settings[:http_proxy_host] = 'none' expect(subject.http_proxy_host).to eq(nil) end it "uses environment variable before puppet settings" do Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do Puppet.settings[:http_proxy_host] = 'not.correct' expect(subject.http_proxy_host).to eq(host) end end end describe ".http_proxy_port" do it "should return a proxy port if set in environment" do Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do expect(subject.http_proxy_port).to eq(port) end end it "should return a proxy port if set in config" do Puppet.settings[:http_proxy_port] = port expect(subject.http_proxy_port).to eq(port) end it "uses environment variable before puppet settings" do Puppet::Util.withenv('HTTP_PROXY' => "http://#{host}:#{port}") do Puppet.settings[:http_proxy_port] = 7456 expect(subject.http_proxy_port).to eq(port) end end end describe ".http_proxy_user" do it "should return a proxy user if set in environment" do Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do expect(subject.http_proxy_user).to eq(user) end end it "should return a proxy user if set in config" do Puppet.settings[:http_proxy_user] = user expect(subject.http_proxy_user).to eq(user) end it "should use environment variable before puppet settings" do Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do Puppet.settings[:http_proxy_user] = 'clownpants' expect(subject.http_proxy_user).to eq(user) end end end describe ".http_proxy_password" do it "should return a proxy password if set in environment" do Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do expect(subject.http_proxy_password).to eq(password) end end it "should return a proxy password if set in config" do Puppet.settings[:http_proxy_user] = user Puppet.settings[:http_proxy_password] = password expect(subject.http_proxy_password).to eq(password) end it "should use environment variable before puppet settings" do Puppet::Util.withenv('HTTP_PROXY' => "http://#{user}:#{password}@#{host}:#{port}") do Puppet.settings[:http_proxy_password] = 'clownpants' expect(subject.http_proxy_password).to eq(password) end end end describe ".no_proxy" do no_proxy = '127.0.0.1, localhost' it "should use a no_proxy list if set in environment" do Puppet::Util.withenv('NO_PROXY' => no_proxy) do expect(subject.no_proxy).to eq(no_proxy) end end it "should use a no_proxy list if set in config" do Puppet.settings[:no_proxy] = no_proxy expect(subject.no_proxy).to eq(no_proxy) end it "should use environment variable before puppet settings" do no_proxy_puppet_setting = '10.0.0.1, localhost' Puppet::Util.withenv('NO_PROXY' => no_proxy) do Puppet.settings[:no_proxy] = no_proxy_puppet_setting expect(subject.no_proxy).to eq(no_proxy) end end end describe ".no_proxy?" do no_proxy = '127.0.0.1, localhost, mydomain.com, *.otherdomain.com, oddport.com:8080, *.otheroddport.com:8080, .anotherdomain.com, .anotheroddport.com:8080' it "should return false if no_proxy does not exist in environment or puppet settings" do Puppet::Util.withenv('no_proxy' => nil) do dest = 'https://puppetlabs.com' expect(subject.no_proxy?(dest)).to be false end end it "should return false if the dest does not match any element in the no_proxy list" do Puppet::Util.withenv('no_proxy' => no_proxy) do dest = 'https://puppetlabs.com' expect(subject.no_proxy?(dest)).to be false end end it "should return true if the dest as an IP does match any element in the no_proxy list" do Puppet::Util.withenv('no_proxy' => no_proxy) do dest = 'http://127.0.0.1' expect(subject.no_proxy?(dest)).to be true end end it "should return true if the dest as single word does match any element in the no_proxy list" do Puppet::Util.withenv('no_proxy' => no_proxy) do dest = 'http://localhost' expect(subject.no_proxy?(dest)).to be true end end it "should return true if the dest as standard domain word does match any element in the no_proxy list" do Puppet::Util.withenv('no_proxy' => no_proxy) do dest = 'http://mydomain.com' expect(subject.no_proxy?(dest)).to be true end end it "should return true if the dest as standard domain with port does match any element in the no_proxy list" do Puppet::Util.withenv('no_proxy' => no_proxy) do dest = 'http://oddport.com:8080' expect(subject.no_proxy?(dest)).to be true end end it "should return false if the dest is standard domain not matching port" do Puppet::Util.withenv('no_proxy' => no_proxy) do dest = 'http://oddport.com' expect(subject.no_proxy?(dest)).to be false end end it "should return true if the dest does match any wildcarded element in the no_proxy list" do Puppet::Util.withenv('no_proxy' => no_proxy) do dest = 'http://sub.otherdomain.com' expect(subject.no_proxy?(dest)).to be true end end it "should return true if the dest does match any wildcarded element with port in the no_proxy list" do Puppet::Util.withenv('no_proxy' => no_proxy) do dest = 'http://sub.otheroddport.com:8080' expect(subject.no_proxy?(dest)).to be true end end it "should return true if the dest does match any domain level (no wildcard) element in the no_proxy list" do Puppet::Util.withenv('no_proxy' => no_proxy) do dest = 'http://sub.anotherdomain.com' expect(subject.no_proxy?(dest)).to be true end end it "should return true if the dest does match any domain level (no wildcard) element with port in the no_proxy list" do Puppet::Util.withenv('no_proxy' => no_proxy) do dest = 'http://sub.anotheroddport.com:8080' expect(subject.no_proxy?(dest)).to be true end end it "should work if passed a URI object" do Puppet::Util.withenv('no_proxy' => no_proxy) do dest = URI.parse('http://sub.otheroddport.com:8080') expect(subject.no_proxy?(dest)).to be true end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/session_spec.rb
spec/unit/http/session_spec.rb
require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::Session do let(:ssl_context) { Puppet::SSL::SSLContext.new } let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) } let(:uri) { URI.parse('https://www.example.com') } let(:good_service) { double('good', url: uri, connect: nil) } let(:bad_service) { create_bad_service } def create_bad_service(failure_message = 'whoops') service = double('bad', url: uri) allow(service).to receive(:connect).and_raise(Puppet::HTTP::ConnectionError, failure_message) service end class DummyResolver < Puppet::HTTP::Resolver attr_reader :count def initialize(service) @service = service @count = 0 end def resolve(session, name, ssl_context: nil, canceled_handler: nil) @count += 1 return @service if check_connection?(session, @service, ssl_context: ssl_context) end end context 'when routing' do it 'returns the first resolved service' do resolvers = [DummyResolver.new(bad_service), DummyResolver.new(good_service)] session = described_class.new(client, resolvers) resolved = session.route_to(:ca) expect(resolved).to eq(good_service) end it 'only resolves once per session' do resolver = DummyResolver.new(good_service) session = described_class.new(client, [resolver]) session.route_to(:ca) session.route_to(:ca) expect(resolver.count).to eq(1) end it 'raises if there are no more routes' do resolvers = [DummyResolver.new(bad_service)] session = described_class.new(client, resolvers) expect { session.route_to(:ca) }.to raise_error(Puppet::HTTP::RouteError, 'No more routes to ca') end it 'logs all routing failures as errors when there are no more routes' do resolvers = [DummyResolver.new(create_bad_service('whoops1')), DummyResolver.new(create_bad_service('whoops2'))] session = described_class.new(client, resolvers) expect { session.route_to(:ca) }.to raise_error(Puppet::HTTP::RouteError, 'No more routes to ca') expect(@logs).to include(an_object_having_attributes(level: :err, message: "Connection to #{uri} failed, trying next route: whoops1"), an_object_having_attributes(level: :err, message: "Connection to #{uri} failed, trying next route: whoops2")) end it 'accepts an ssl context to use when connecting' do alt_context = Puppet::SSL::SSLContext.new expect(good_service).to receive(:connect).with(ssl_context: alt_context) resolvers = [DummyResolver.new(good_service)] session = described_class.new(client, resolvers) session.route_to(:ca, ssl_context: alt_context) end it 'raises for unknown service names' do expect { session = described_class.new(client, []) session.route_to(:westbound) }.to raise_error(ArgumentError, "Unknown service westbound") end it 'routes to the service when given a puppet URL with an explicit host' do allow_any_instance_of(Net::HTTP).to receive(:start) session = described_class.new(client, []) url = URI("puppet://example.com:8140/:modules/:module/path/to/file") service = session.route_to(:fileserver, url: url) expect(service.url.to_s).to eq("https://example.com:8140/puppet/v3") end it 'raises a connection error if we cannot connect' do allow_any_instance_of(Net::HTTP).to receive(:start).and_raise(Net::OpenTimeout) session = described_class.new(client, []) url = URI('puppet://example.com:8140/:modules/:module/path/to/file') expect { session.route_to(:fileserver, url: url) }.to raise_error(Puppet::HTTP::ConnectionError, %r{Request to https://example.com:8140/puppet/v3 timed out connect operation after .* seconds}) end it 'resolves the route when given a generic puppet:/// URL' do resolvers = [DummyResolver.new(good_service)] session = described_class.new(client, resolvers) url = URI('puppet:///:modules/:module/path/to/file') service = session.route_to(:fileserver, url: url) expect(service.url).to eq(good_service.url) end end context 'when resolving using multiple resolvers' do let(:session) { client.create_session } it "prefers SRV records" do Puppet[:use_srv_records] = true Puppet[:server_list] = 'foo.example.com,bar.example.com,baz.example.com' Puppet[:ca_server] = 'caserver.example.com' allow_any_instance_of(Puppet::HTTP::DNS).to receive(:each_srv_record).and_yield('mars.example.srv', 8140) service = session.route_to(:ca) expect(service.url).to eq(URI("https://mars.example.srv:8140/puppet-ca/v1")) end it "next prefers :ca_server when explicitly set" do Puppet[:use_srv_records] = true Puppet[:server_list] = 'foo.example.com,bar.example.com,baz.example.com' Puppet[:ca_server] = 'caserver.example.com' service = session.route_to(:ca) expect(service.url).to eq(URI("https://caserver.example.com:8140/puppet-ca/v1")) end it "next prefers the first successful connection from server_list" do Puppet[:use_srv_records] = true Puppet[:server_list] = 'foo.example.com,bar.example.com,baz.example.com' allow_any_instance_of(Puppet::HTTP::DNS).to receive(:each_srv_record) stub_request(:get, "https://foo.example.com:8140/status/v1/simple/server").to_return(status: 500) stub_request(:get, "https://bar.example.com:8140/status/v1/simple/server").to_return(status: 200) service = session.route_to(:ca) expect(service.url).to eq(URI("https://bar.example.com:8140/puppet-ca/v1")) end it "does not fallback from server_list to the settings resolver when server_list is exhausted" do Puppet[:server_list] = 'foo.example.com' expect_any_instance_of(Puppet::HTTP::Resolver::Settings).to receive(:resolve).never stub_request(:get, "https://foo.example.com:8140/status/v1/simple/server").to_return(status: 500) expect { session.route_to(:ca) }.to raise_error(Puppet::HTTP::RouteError, "No more routes to ca") end it "raises when there are no more routes" do allow_any_instance_of(Net::HTTP).to receive(:start).and_raise(Errno::EHOSTUNREACH) session = client.create_session expect { session.route_to(:ca) }.to raise_error(Puppet::HTTP::RouteError, 'No more routes to ca') end Puppet::HTTP::Service::SERVICE_NAMES.each do |name| it "resolves #{name} using server_list" do Puppet[:server_list] = 'apple.example.com' req = stub_request(:get, "https://apple.example.com:8140/status/v1/simple/server").to_return(status: 200) session.route_to(name) expect(req).to have_been_requested end end it 'does not use server_list to resolve the ca service when ca_server is explicitly set' do Puppet[:ca_server] = 'banana.example.com' expect(session.route_to(:ca).url.to_s).to eq("https://banana.example.com:8140/puppet-ca/v1") end it 'does not use server_list to resolve the report service when the report_server is explicitly set' do Puppet[:report_server] = 'cherry.example.com' expect(session.route_to(:report).url.to_s).to eq("https://cherry.example.com:8140/puppet/v3") end it 'resolves once for all services in a session' do Puppet[:server_list] = 'apple.example.com' req = stub_request(:get, "https://apple.example.com:8140/status/v1/simple/server").to_return(status: 200) Puppet::HTTP::Service::SERVICE_NAMES.each do |name| session.route_to(name) end expect(req).to have_been_requested end it 'resolves server_list for each new session' do Puppet[:server_list] = 'apple.example.com' req = stub_request(:get, "https://apple.example.com:8140/status/v1/simple/server").to_return(status: 200) client.create_session.route_to(:puppet) client.create_session.route_to(:puppet) expect(req).to have_been_requested.twice end end context 'when retrieving capabilities' do let(:response) { Puppet::HTTP::Response.new(uri, 200, 'OK') } let(:session) do resolver = DummyResolver.new(good_service) described_class.new(client, [resolver]) end it 'raises for unknown service names' do expect { session = described_class.new(client, []) session.supports?(:westbound, 'a capability') }.to raise_error(ArgumentError, "Unknown service westbound") end context 'locales' do it 'does not support locales if the cached service has not been resolved' do session = described_class.new(client, []) expect(session).to_not be_supports(:puppet, 'locales') end it "supports locales if the cached service's version is 5.3.4 or greater" do allow(response).to receive(:[]).with('X-Puppet-Version').and_return('5.3.4') session.route_to(:puppet) session.process_response(response) expect(session).to be_supports(:puppet, 'locales') end it "does not support locales if the cached service's version is 5.3.3" do allow(response).to receive(:[]).with('X-Puppet-Version').and_return('5.3.3') session.route_to(:puppet) session.process_response(response) expect(session).to_not be_supports(:puppet, 'locales') end it "does not support locales if the cached service's version is missing" do allow(response).to receive(:[]).with('X-Puppet-Version').and_return(nil) session.route_to(:puppet) session.process_response(response) expect(session).to_not be_supports(:puppet, 'locales') end end context 'json' do it 'does not support json if the cached service has not been resolved' do session = described_class.new(client, []) expect(session).to_not be_supports(:puppet, 'json') end it "supports json if the cached service's version is 5 or greater" do allow(response).to receive(:[]).with('X-Puppet-Version').and_return('5.5.12') session.route_to(:puppet) session.process_response(response) expect(session).to be_supports(:puppet, 'json') end it "does not support json if the cached service's version is less than 5.0" do allow(response).to receive(:[]).with('X-Puppet-Version').and_return('4.10.1') session.route_to(:puppet) session.process_response(response) expect(session).to_not be_supports(:puppet, 'json') end it "supports json if the cached service's version is missing" do allow(response).to receive(:[]).with('X-Puppet-Version').and_return(nil) session.route_to(:puppet) session.process_response(response) expect(session).to be_supports(:puppet, 'json') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/factory_spec.rb
spec/unit/http/factory_spec.rb
require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::Factory do before(:all) do ENV['http_proxy'] = nil ENV['HTTP_PROXY'] = nil end let(:site) { Puppet::HTTP::Site.new('https', 'www.example.com', 443) } def create_connection(site) factory = described_class.new factory.create_connection(site) end it 'creates a connection for the site' do conn = create_connection(site) expect(conn.use_ssl?).to be_truthy expect(conn.address).to eq(site.host) expect(conn.port).to eq(site.port) end it 'creates a connection that has not yet been started' do conn = create_connection(site) expect(conn).to_not be_started end it 'creates a connection supporting at least HTTP 1.1' do conn = create_connection(site) expect(conn.class.version_1_1? || conn.class.version_1_2?).to be_truthy end context "proxy settings" do let(:proxy_host) { 'myhost' } let(:proxy_port) { 432 } let(:proxy_user) { 'mo' } let(:proxy_pass) { 'password' } it "should not set a proxy if the http_proxy_host setting is 'none'" do Puppet[:http_proxy_host] = 'none' conn = create_connection(site) expect(conn.proxy_address).to be_nil end it 'should not set a proxy if a no_proxy env var matches the destination' do Puppet[:http_proxy_host] = proxy_host Puppet[:http_proxy_port] = proxy_port Puppet::Util.withenv('NO_PROXY' => site.host) do conn = create_connection(site) expect(conn.proxy_address).to be_nil expect(conn.proxy_port).to be_nil end end it 'should not set a proxy if the no_proxy setting matches the destination' do Puppet[:http_proxy_host] = proxy_host Puppet[:http_proxy_port] = proxy_port Puppet[:no_proxy] = site.host conn = create_connection(site) expect(conn.proxy_address).to be_nil expect(conn.proxy_port).to be_nil end it 'sets proxy_address' do Puppet[:http_proxy_host] = proxy_host conn = create_connection(site) expect(conn.proxy_address).to eq(proxy_host) end it 'sets proxy address and port' do Puppet[:http_proxy_host] = proxy_host Puppet[:http_proxy_port] = proxy_port conn = create_connection(site) expect(conn.proxy_port).to eq(proxy_port) end it 'sets proxy user and password' do Puppet[:http_proxy_host] = proxy_host Puppet[:http_proxy_port] = proxy_port Puppet[:http_proxy_user] = proxy_user Puppet[:http_proxy_password] = proxy_pass conn = create_connection(site) expect(conn.proxy_user).to eq(proxy_user) expect(conn.proxy_pass).to eq(proxy_pass) end end context 'socket timeouts' do it 'sets open timeout' do Puppet[:http_connect_timeout] = "10s" conn = create_connection(site) expect(conn.open_timeout).to eq(10) end it 'sets read timeout' do Puppet[:http_read_timeout] = "2m" conn = create_connection(site) expect(conn.read_timeout).to eq(120) end end it "disables ruby's http_keepalive_timeout" do conn = create_connection(site) expect(conn.keep_alive_timeout).to eq(2147483647) end it "disables ruby's max retry" do conn = create_connection(site) expect(conn.max_retries).to eq(0) end context 'source address' do it 'defaults to system-defined' do conn = create_connection(site) expect(conn.local_host).to be(nil) end it 'sets the local_host address' do Puppet[:sourceaddress] = "127.0.0.1" conn = create_connection(site) expect(conn.local_host).to eq('127.0.0.1') end end context 'tls' do it "sets the minimum version to TLS 1.0" do conn = create_connection(site) expect(conn.min_version).to eq(OpenSSL::SSL::TLS1_VERSION) end it "defaults to ciphersuites providing 128 bits of security or greater" do conn = create_connection(site) expect(conn.ciphers).to eq("ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256") end it "can be restricted to TLSv1.3 ciphers" do tls13_ciphers = "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256" Puppet[:ciphers] = tls13_ciphers conn = create_connection(site) expect(conn.ciphers).to eq(tls13_ciphers) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/service_spec.rb
spec/unit/http/service_spec.rb
require 'spec_helper' require 'puppet_spec/network' require 'puppet/http' require 'puppet/file_serving' require 'puppet/file_serving/content' require 'puppet/file_serving/metadata' describe Puppet::HTTP::Service do include PuppetSpec::Network let(:ssl_context) { Puppet::SSL::SSLContext.new } let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) } let(:session) { Puppet::HTTP::Session.new(client, []) } let(:url) { URI.parse('https://www.example.com') } let(:service) { described_class.new(client, session, url) } class TestService < Puppet::HTTP::Service def get_test(ssl_context) @client.get( url, headers: add_puppet_headers({'Default-Header' => 'default-value'}), options: {ssl_context: ssl_context} ) end def mime_types(model) get_mime_types(model) end end context 'when modifying headers for an http request' do let(:service) { TestService.new(client, session, url) } it 'adds custom user-specified headers' do stub_request(:get, "https://www.example.com/"). with( headers: { 'Default-Header'=>'default-value', 'Header2'=>'newvalue' }) Puppet[:http_extra_headers] = 'header2:newvalue' service.get_test(ssl_context) end it 'adds X-Puppet-Profiling header if set' do stub_request(:get, "https://www.example.com/"). with( headers: { 'Default-Header'=>'default-value', 'X-Puppet-Profiling'=>'true' }) Puppet[:profile] = true service.get_test(ssl_context) end it 'ignores a custom header does not have a value' do stub_request(:get, "https://www.example.com/").with do |request| expect(request.headers).to include({'Default-Header' => 'default-value'}) expect(request.headers).to_not include('header-with-no-value') end Puppet[:http_extra_headers] = 'header-with-no-value:' service.get_test(ssl_context) end it 'ignores a custom header that already exists (case insensitive) in the header hash' do stub_request(:get, "https://www.example.com/"). with( headers: { 'Default-Header'=>'default-value' }) Puppet[:http_extra_headers] = 'default-header:wrongvalue' service.get_test(ssl_context) end end it "returns a URI containing the base URL and path" do expect(service.with_base_url('/puppet/v3')).to eq(URI.parse("https://www.example.com/puppet/v3")) end it "doesn't modify frozen the base URL" do service = described_class.new(client, session, url.freeze) service.with_base_url('/puppet/v3') end it "percent encodes paths before appending them to the path" do expect(service.with_base_url('/path/with/a space')).to eq(URI.parse("https://www.example.com/path/with/a%20space")) end it "connects to the base URL with a nil ssl context" do expect(client).to receive(:connect).with(url, options: {ssl_context: nil}) service.connect end it "accepts an optional ssl_context" do other_ctx = Puppet::SSL::SSLContext.new expect(client).to receive(:connect).with(url, options: {ssl_context: other_ctx}) service.connect(ssl_context: other_ctx) end it 'raises for unknown service names' do expect { described_class.create_service(client, session, :westbound) }.to raise_error(ArgumentError, "Unknown service westbound") end [:ca].each do |name| it "returns true for #{name}" do expect(described_class.valid_name?(name)).to eq(true) end end it "returns false when the service name is a string" do expect(described_class.valid_name?("ca")).to eq(false) end it "returns false for unknown service names" do expect(described_class.valid_name?(:westbound)).to eq(false) end it 'returns different mime types for different models' do mimes = acceptable_content_types service = TestService.new(client, session, url) [ Puppet::Node, Puppet::Node::Facts, Puppet::Transaction::Report, Puppet::FileServing::Metadata, ].each do |model| expect(service.mime_types(model)).to eq(mimes) end # These are special expect(service.mime_types(Puppet::FileServing::Content)).to eq(%w[application/octet-stream]) expect(service.mime_types(Puppet::Resource::Catalog)).to eq(acceptable_catalog_content_types) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/dns_spec.rb
spec/unit/http/dns_spec.rb
require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::DNS do before do @dns_mock_object = double('dns') allow(Resolv::DNS).to receive(:new).and_return(@dns_mock_object) @rr_type = Resolv::DNS::Resource::IN::SRV @test_srv_domain = "domain.com" @test_a_hostname = "puppet.domain.com" @test_port = 1000 # The records we should use. @test_records = [ # priority, weight, port, target Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "puppet1.domain.com"), Resolv::DNS::Resource::IN::SRV.new(0, 80, 8140, "puppet2.domain.com"), Resolv::DNS::Resource::IN::SRV.new(1, 1, 8140, "puppet3.domain.com"), Resolv::DNS::Resource::IN::SRV.new(4, 1, 8140, "puppet4.domain.com") ] @test_records.each do |rec| # Resources do not expose public API for setting the TTL rec.instance_variable_set(:@ttl, 3600) end end let(:resolver) { described_class.new } describe 'when the domain is not known' do before :each do allow(@dns_mock_object).to receive(:getresources).and_return(@test_records) end describe 'because domain is nil' do it 'does not yield' do resolver.each_srv_record(nil) do |_,_,_| raise Exception.new("nil domain caused SRV lookup") end end end describe 'because domain is an empty string' do it 'does not yield' do resolver.each_srv_record('') do |_,_,_| raise Exception.new("nil domain caused SRV lookup") end end end end describe "when resolving a host without SRV records" do it "should not yield anything" do # No records returned for a DNS entry without any SRV records expect(@dns_mock_object).to receive(:getresources).with( "_x-puppet._tcp.#{@test_a_hostname}", @rr_type ).and_return([]) resolver.each_srv_record(@test_a_hostname) do |hostname, port, remaining| raise Exception.new("host with no records passed block") end end end describe "when resolving a host with SRV records" do it "should iterate through records in priority order" do # The order of the records that should be returned, # an array means unordered (for weight) order = { 0 => ["puppet1.domain.com", "puppet2.domain.com"], 1 => ["puppet3.domain.com"], 2 => ["puppet4.domain.com"] } expect(@dns_mock_object).to receive(:getresources).with( "_x-puppet._tcp.#{@test_srv_domain}", @rr_type ).and_return(@test_records) resolver.each_srv_record(@test_srv_domain) do |hostname, port| expected_priority = order.keys.min expect(order[expected_priority]).to include(hostname) expect(port).not_to be(@test_port) # Remove the host from our expected hosts order[expected_priority].delete hostname # Remove this priority level if we're done with it order.delete expected_priority if order[expected_priority] == [] end end it "should fall back to the :puppet service if no records are found for a more specific service" do # The order of the records that should be returned, # an array means unordered (for weight) order = { 0 => ["puppet1.domain.com", "puppet2.domain.com"], 1 => ["puppet3.domain.com"], 2 => ["puppet4.domain.com"] } expect(@dns_mock_object).to receive(:getresources).with( "_x-puppet-report._tcp.#{@test_srv_domain}", @rr_type ).and_return([]) expect(@dns_mock_object).to receive(:getresources).with( "_x-puppet._tcp.#{@test_srv_domain}", @rr_type ).and_return(@test_records) resolver.each_srv_record(@test_srv_domain, :report) do |hostname, port| expected_priority = order.keys.min expect(order[expected_priority]).to include(hostname) expect(port).not_to be(@test_port) # Remove the host from our expected hosts order[expected_priority].delete hostname # Remove this priority level if we're done with it order.delete expected_priority if order[expected_priority] == [] end end it "should use SRV records from the specific service if they exist" do # The order of the records that should be returned, # an array means unordered (for weight) order = { 0 => ["puppet1.domain.com", "puppet2.domain.com"], 1 => ["puppet3.domain.com"], 2 => ["puppet4.domain.com"] } bad_records = [ # priority, weight, port, hostname Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "puppet1.bad.domain.com"), Resolv::DNS::Resource::IN::SRV.new(0, 80, 8140, "puppet2.bad.domain.com"), Resolv::DNS::Resource::IN::SRV.new(1, 1, 8140, "puppet3.bad.domain.com"), Resolv::DNS::Resource::IN::SRV.new(4, 1, 8140, "puppet4.bad.domain.com") ] expect(@dns_mock_object).to receive(:getresources).with( "_x-puppet-report._tcp.#{@test_srv_domain}", @rr_type ).and_return(@test_records) allow(@dns_mock_object).to receive(:getresources).with( "_x-puppet._tcp.#{@test_srv_domain}", @rr_type ).and_return(bad_records) resolver.each_srv_record(@test_srv_domain, :report) do |hostname, port| expected_priority = order.keys.min expect(order[expected_priority]).to include(hostname) expect(port).not_to be(@test_port) # Remove the host from our expected hosts order[expected_priority].delete hostname # Remove this priority level if we're done with it order.delete expected_priority if order[expected_priority] == [] end end end describe "when finding weighted servers" do it "should return nil when no records were found" do expect(resolver.find_weighted_server([])).to eq(nil) end it "should return the first record when one record is passed" do result = resolver.find_weighted_server([@test_records.first]) expect(result).to eq(@test_records.first) end { "all have weights" => [1, 3, 2, 4], "some have weights" => [2, 0, 1, 0], "none have weights" => [0, 0, 0, 0], }.each do |name, weights| it "should return correct results when #{name}" do records = [] count = 0 weights.each do |w| count += 1 # priority, weight, port, server records << Resolv::DNS::Resource::IN::SRV.new(0, w, 1, count.to_s) end seen = Hash.new(0) total_weight = records.inject(0) do |sum, record| sum + resolver.weight(record) end total_weight.times do |n| expect(Kernel).to receive(:rand).once.with(total_weight).and_return(n) server = resolver.find_weighted_server(records) seen[server] += 1 end expect(seen.length).to eq(records.length) records.each do |record| expect(seen[record]).to eq(resolver.weight(record)) end end end end describe "caching records" do it "should query DNS when no cache entry exists, then retrieve the cached value" do expect(@dns_mock_object).to receive(:getresources).with( "_x-puppet._tcp.#{@test_srv_domain}", @rr_type ).and_return(@test_records).once fetched_servers = [] resolver.each_srv_record(@test_srv_domain) do |server, port| fetched_servers << server end cached_servers = [] expect(resolver).to receive(:expired?).and_return(false) resolver.each_srv_record(@test_srv_domain) do |server, port| cached_servers << server end expect(fetched_servers).to match_array(cached_servers) end context "TTLs" do before(:each) do # The TTL of an SRV record cannot be set via any public API ttl_record1 = Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "puppet1.domain.com") ttl_record1.instance_variable_set(:@ttl, 10) ttl_record2 = Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "puppet2.domain.com") ttl_record2.instance_variable_set(:@ttl, 20) records = [ttl_record1, ttl_record2] expect(@dns_mock_object).to receive(:getresources).with( "_x-puppet._tcp.#{@test_srv_domain}", @rr_type ).and_return(records) end it "should save the shortest TTL among records for a service" do resolver.each_srv_record(@test_srv_domain) { |server, port| } expect(resolver.ttl(:puppet)).to eq(10) end it "should fetch records again if the TTL has expired" do # Fetch from DNS resolver.each_srv_record(@test_srv_domain) do |server, port| expect(server).to match(/puppet.*domain\.com/) end expect(resolver).to receive(:expired?).with(:puppet).and_return(false) # Load from cache resolver.each_srv_record(@test_srv_domain) do |server, port| expect(server).to match(/puppet.*domain\.com/) end new_record = Resolv::DNS::Resource::IN::SRV.new(0, 20, 8140, "new.domain.com") new_record.instance_variable_set(:@ttl, 10) expect(@dns_mock_object).to receive(:getresources).with( "_x-puppet._tcp.#{@test_srv_domain}", @rr_type ).and_return([new_record]) expect(resolver).to receive(:expired?).with(:puppet).and_return(true) # Refresh from DNS resolver.each_srv_record(@test_srv_domain) do |server, port| expect(server).to eq("new.domain.com") end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/resolver_spec.rb
spec/unit/http/resolver_spec.rb
require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::Resolver do let(:ssl_context) { Puppet::SSL::SSLContext.new } let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) } let(:session) { client.create_session } let(:uri) { URI.parse('https://www.example.com') } context 'when resolving using settings' do let(:subject) { Puppet::HTTP::Resolver::Settings.new(client) } it 'returns a service based on the current ca_server and ca_port settings' do Puppet[:ca_server] = 'ca.example.com' Puppet[:ca_port] = 8141 service = subject.resolve(session, :ca) expect(service).to be_an_instance_of(Puppet::HTTP::Service::Ca) expect(service.url.to_s).to eq("https://ca.example.com:8141/puppet-ca/v1") end end context 'when resolving using server_list' do let(:subject) { Puppet::HTTP::Resolver::ServerList.new(client, server_list_setting: Puppet.settings.setting(:server_list), default_port: 8142, services: Puppet::HTTP::Service::SERVICE_NAMES) } before :each do Puppet[:server_list] = 'ca.example.com:8141,apple.example.com' end it 'returns a service based on the current server_list setting' do stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 200) service = subject.resolve(session, :ca) expect(service).to be_an_instance_of(Puppet::HTTP::Service::Ca) expect(service.url.to_s).to eq("https://ca.example.com:8141/puppet-ca/v1") end it 'returns a service based on the current server_list setting if the server returns any success codes' do stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 202) service = subject.resolve(session, :ca) expect(service).to be_an_instance_of(Puppet::HTTP::Service::Ca) expect(service.url.to_s).to eq("https://ca.example.com:8141/puppet-ca/v1") end it 'includes extra http headers' do Puppet[:http_extra_headers] = 'region:us-west' stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server") .with(headers: {'Region' => 'us-west'}) subject.resolve(session, :ca) end it 'uses the provided ssl context during resolution' do stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 200) other_ctx = Puppet::SSL::SSLContext.new expect(client).to receive(:connect).with(URI("https://ca.example.com:8141/status/v1/simple/server"), options: {ssl_context: other_ctx}).and_call_original subject.resolve(session, :ca, ssl_context: other_ctx) end it 'logs unsuccessful HTTP 500 responses' do stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: [500, 'Internal Server Error']) stub_request(:get, "https://apple.example.com:8142/status/v1/simple/server").to_return(status: 200) subject.resolve(session, :ca) expect(@logs.map(&:message)).to include(/Puppet server ca.example.com:8141 is unavailable: 500 Internal Server Error/) end it 'cancels resolution if no servers in server_list are accessible' do stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 503) stub_request(:get, "https://apple.example.com:8142/status/v1/simple/server").to_return(status: 503) canceled = false canceled_handler = lambda { |cancel| canceled = cancel } expect(subject.resolve(session, :ca, canceled_handler: canceled_handler)).to eq(nil) expect(canceled).to eq(true) end it 'cycles through server_list until a valid server is found' do stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 503) stub_request(:get, "https://apple.example.com:8142/status/v1/simple/server").to_return(status: 200) service = subject.resolve(session, :ca) expect(service).to be_an_instance_of(Puppet::HTTP::Service::Ca) expect(service.url.to_s).to eq("https://apple.example.com:8142/puppet-ca/v1") end it 'resolves once per session' do failed = stub_request(:get, "https://ca.example.com:8141/status/v1/simple/server").to_return(status: 503) passed = stub_request(:get, "https://apple.example.com:8142/status/v1/simple/server").to_return(status: 200) service = subject.resolve(session, :puppet) expect(service).to be_a(Puppet::HTTP::Service::Compiler) expect(service.url.to_s).to eq("https://apple.example.com:8142/puppet/v3") service = subject.resolve(session, :fileserver) expect(service).to be_a(Puppet::HTTP::Service::FileServer) expect(service.url.to_s).to eq("https://apple.example.com:8142/puppet/v3") service = subject.resolve(session, :report) expect(service).to be_a(Puppet::HTTP::Service::Report) expect(service.url.to_s).to eq("https://apple.example.com:8142/puppet/v3") expect(failed).to have_been_requested expect(passed).to have_been_requested end end context 'when resolving using SRV' do let(:dns) { double('dns') } let(:subject) { Puppet::HTTP::Resolver::SRV.new(client, domain: 'example.com', dns: dns) } def stub_srv(host, port) srv = Resolv::DNS::Resource::IN::SRV.new(0, 0, port, host) srv.instance_variable_set :@ttl, 3600 allow(dns).to receive(:getresources).with("_x-puppet-ca._tcp.example.com", Resolv::DNS::Resource::IN::SRV).and_return([srv]) end it 'returns a service based on an SRV record' do stub_srv('ca1.example.com', 8142) service = subject.resolve(session, :ca) expect(service).to be_an_instance_of(Puppet::HTTP::Service::Ca) expect(service.url.to_s).to eq("https://ca1.example.com:8142/puppet-ca/v1") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/pool_spec.rb
spec/unit/http/pool_spec.rb
require 'spec_helper' require 'openssl' require 'puppet/network/http' require 'puppet/network/http_pool' describe Puppet::HTTP::Pool do let(:site) do Puppet::HTTP::Site.new('https', 'rubygems.org', 443) end let(:different_site) do Puppet::HTTP::Site.new('https', 'github.com', 443) end let(:ssl_context) { Puppet::SSL::SSLContext.new } let(:verifier) do v = Puppet::SSL::Verifier.new(site.host, ssl_context) allow(v).to receive(:setup_connection) v end def create_pool Puppet::HTTP::Pool.new(15) end def create_pool_with_connections(site, *connections) pool = Puppet::HTTP::Pool.new(15) connections.each do |conn| pool.release(site, verifier, conn) end pool end def create_pool_with_http_connections(site, *connections) pool = Puppet::HTTP::Pool.new(15) connections.each do |conn| pool.release(site, nil, conn) end pool end def create_pool_with_expired_connections(site, *connections) # setting keepalive timeout to -1 ensures any newly added # connections have already expired pool = Puppet::HTTP::Pool.new(-1) connections.each do |conn| pool.release(site, verifier, conn) end pool end def create_connection(site) double(site.addr, :started? => false, :start => nil, :finish => nil, :use_ssl? => true, :verify_mode => OpenSSL::SSL::VERIFY_PEER) end def create_http_connection(site) double(site.addr, :started? => false, :start => nil, :finish => nil, :use_ssl? => false) end context 'when yielding a connection' do it 'yields a connection' do conn = create_connection(site) pool = create_pool_with_connections(site, conn) expect { |b| pool.with_connection(site, verifier, &b) }.to yield_with_args(conn) end it 'returns the connection to the pool' do conn = create_connection(site) expect(conn).to receive(:started?).and_return(true) pool = create_pool pool.release(site, verifier, conn) pool.with_connection(site, verifier) { |c| } expect(pool.pool[site].first.connection).to eq(conn) end it 'can yield multiple connections to the same site' do lru_conn = create_connection(site) mru_conn = create_connection(site) pool = create_pool_with_connections(site, lru_conn, mru_conn) pool.with_connection(site, verifier) do |a| expect(a).to eq(mru_conn) pool.with_connection(site, verifier) do |b| expect(b).to eq(lru_conn) end end end it 'propagates exceptions' do conn = create_connection(site) pool = create_pool pool.release(site, verifier, conn) expect { pool.with_connection(site, verifier) do |c| raise IOError, 'connection reset' end }.to raise_error(IOError, 'connection reset') end it 'does not re-cache connections when an error occurs' do # we're not distinguishing between network errors that would # suggest we close the socket, and other errors conn = create_connection(site) pool = create_pool pool.release(site, verifier, conn) expect(pool).not_to receive(:release).with(site, verifier, conn) pool.with_connection(site, verifier) do |c| raise IOError, 'connection reset' end rescue nil end it 'sets keepalive bit on network socket' do pool = create_pool s = Socket.new(Socket::PF_INET, Socket::SOCK_STREAM) pool.setsockopts(Net::BufferedIO.new(s)) # On windows, Socket.getsockopt() doesn't return exactly the same data # as an equivalent Socket::Option.new() statement, so we strip off the # unrelevant bits only on this platform. # # To make sure we're not voiding the test case by doing this, we check # both with and without the keepalive bit set. # # This workaround can be removed once all the ruby versions we care about # have the patch from https://bugs.ruby-lang.org/issues/11958 applied. # if Puppet::Util::Platform.windows? keepalive = Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, true).data[0] nokeepalive = Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, false).data[0] expect(s.getsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE).data).to eq(keepalive) expect(s.getsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE).data).to_not eq(nokeepalive) else expect(s.getsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE).bool).to eq(true) end end context 'when releasing connections' do it 'releases HTTP connections' do conn = create_connection(site) expect(conn).to receive(:use_ssl?).and_return(false) expect(conn).to receive(:started?).and_return(true) pool = create_pool_with_connections(site, conn) expect(pool).to receive(:release).with(site, verifier, conn) pool.with_connection(site, verifier) {|c| } end it 'releases secure HTTPS connections' do conn = create_connection(site) expect(conn).to receive(:use_ssl?).and_return(true) expect(conn).to receive(:verify_mode).and_return(OpenSSL::SSL::VERIFY_PEER) expect(conn).to receive(:started?).and_return(true) pool = create_pool_with_connections(site, conn) expect(pool).to receive(:release).with(site, verifier, conn) pool.with_connection(site, verifier) {|c| } end it 'closes insecure HTTPS connections' do conn = create_connection(site) expect(conn).to receive(:use_ssl?).and_return(true) expect(conn).to receive(:verify_mode).and_return(OpenSSL::SSL::VERIFY_NONE) pool = create_pool_with_connections(site, conn) expect(pool).not_to receive(:release).with(site, verifier, conn) pool.with_connection(site, verifier) {|c| } end it "doesn't add a closed connection back to the pool" do http = Net::HTTP.new(site.addr) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.start pool = create_pool_with_connections(site, http) pool.with_connection(site, verifier) {|c| c.finish} expect(pool.pool[site]).to be_nil end end end context 'when borrowing' do it 'returns a new connection if the pool is empty' do conn = create_connection(site) pool = create_pool expect(pool.factory).to receive(:create_connection).with(site).and_return(conn) expect(pool.borrow(site, verifier)).to eq(conn) end it 'returns a matching connection' do conn = create_connection(site) pool = create_pool_with_connections(site, conn) expect(pool.factory).not_to receive(:create_connection) expect(pool.borrow(site, verifier)).to eq(conn) end it 'returns a new connection if there are no matching sites' do different_conn = create_connection(different_site) pool = create_pool_with_connections(different_site, different_conn) conn = create_connection(site) expect(pool.factory).to receive(:create_connection).with(site).and_return(conn) expect(pool.borrow(site, verifier)).to eq(conn) end it 'returns a new HTTP connection if the cached connection is HTTPS' do https_site = Puppet::HTTP::Site.new('https', 'www.example.com', 443) old_conn = create_connection(https_site) pool = create_pool_with_connections(https_site, old_conn) http_site = Puppet::HTTP::Site.new('http', 'www.example.com', 443) new_conn = create_http_connection(http_site) allow(pool.factory).to receive(:create_connection).with(http_site).and_return(new_conn) expect(pool.borrow(http_site, nil)).to eq(new_conn) end it 'returns a new HTTPS connection if the cached connection is HTTP' do http_site = Puppet::HTTP::Site.new('http', 'www.example.com', 443) old_conn = create_http_connection(http_site) pool = create_pool_with_http_connections(http_site, old_conn) https_site = Puppet::HTTP::Site.new('https', 'www.example.com', 443) new_conn = create_connection(https_site) allow(pool.factory).to receive(:create_connection).with(https_site).and_return(new_conn) expect(pool.borrow(https_site, verifier)).to eq(new_conn) end it 'returns a new connection if the ssl contexts are different' do old_conn = create_connection(site) pool = create_pool_with_connections(site, old_conn) new_conn = create_connection(site) allow(pool.factory).to receive(:create_connection).with(site).and_return(new_conn) new_verifier = Puppet::SSL::Verifier.new(site.host, Puppet::SSL::SSLContext.new) allow(new_verifier).to receive(:setup_connection) # 'equal' tests that it's the same object expect(pool.borrow(site, new_verifier)).to eq(new_conn) end it 'returns a cached connection if the ssl contexts are the same' do old_conn = create_connection(site) pool = create_pool_with_connections(site, old_conn) expect(pool.factory).not_to receive(:create_connection) # 'equal' tests that it's the same object new_verifier = Puppet::SSL::Verifier.new(site.host, ssl_context) expect(pool.borrow(site, new_verifier)).to equal(old_conn) end it 'returns a cached connection if both connections are http' do http_site = Puppet::HTTP::Site.new('http', 'www.example.com', 80) old_conn = create_http_connection(http_site) pool = create_pool_with_http_connections(http_site, old_conn) # 'equal' tests that it's the same object expect(pool.borrow(http_site, nil)).to equal(old_conn) end it 'returns started connections' do conn = create_connection(site) expect(conn).to receive(:start) pool = create_pool expect(pool.factory).to receive(:create_connection).with(site).and_return(conn) expect(pool.borrow(site, verifier)).to eq(conn) end it "doesn't start a cached connection" do conn = create_connection(site) expect(conn).not_to receive(:start) pool = create_pool_with_connections(site, conn) pool.borrow(site, verifier) end it 'returns the most recently used connection from the pool' do least_recently_used = create_connection(site) most_recently_used = create_connection(site) pool = create_pool_with_connections(site, least_recently_used, most_recently_used) expect(pool.borrow(site, verifier)).to eq(most_recently_used) end it 'finishes expired connections' do conn = create_connection(site) allow(conn).to receive(:started?).and_return(true) expect(conn).to receive(:finish) pool = create_pool_with_expired_connections(site, conn) expect(pool.factory).to receive(:create_connection).and_return(double('conn', :start => nil, :use_ssl? => true)) pool.borrow(site, verifier) end it 'logs an exception if it fails to close an expired connection' do expect(Puppet).to receive(:log_exception).with(be_a(IOError), "Failed to close connection for #{site}: read timeout") conn = create_connection(site) expect(conn).to receive(:started?).and_return(true) expect(conn).to receive(:finish).and_raise(IOError, 'read timeout') pool = create_pool_with_expired_connections(site, conn) expect(pool.factory).to receive(:create_connection).and_return(double('open_conn', :start => nil, :use_ssl? => true)) pool.borrow(site, verifier) end it 'deletes the session when the last connection is borrowed' do conn = create_connection(site) pool = create_pool_with_connections(site, conn) pool.borrow(site, verifier) expect(pool.pool[site]).to be_nil end end context 'when releasing a connection' do it 'adds the connection to an empty pool' do conn = create_connection(site) pool = create_pool pool.release(site, verifier, conn) expect(pool.pool[site].first.connection).to eq(conn) end it 'adds the connection to a pool with a connection for the same site' do pool = create_pool pool.release(site, verifier, create_connection(site)) pool.release(site, verifier, create_connection(site)) expect(pool.pool[site].count).to eq(2) end it 'adds the connection to a pool with a connection for a different site' do pool = create_pool pool.release(site, verifier, create_connection(site)) pool.release(different_site, verifier, create_connection(different_site)) expect(pool.pool[site].count).to eq(1) expect(pool.pool[different_site].count).to eq(1) end end context 'when closing' do it 'clears the pool' do pool = create_pool pool.close expect(pool.pool).to be_empty end it 'closes all cached connections' do conn = create_connection(site) allow(conn).to receive(:started?).and_return(true) expect(conn).to receive(:finish) pool = create_pool_with_connections(site, conn) pool.close end it 'allows a connection to be closed multiple times safely' do http = Net::HTTP.new(site.addr) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.start pool = create_pool expect(pool.close_connection(site, http)).to eq(true) expect(pool.close_connection(site, http)).to eq(false) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/service/ca_spec.rb
spec/unit/http/service/ca_spec.rb
require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::Service::Ca do let(:ssl_context) { Puppet::SSL::SSLContext.new } let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) } let(:session) { Puppet::HTTP::Session.new(client, []) } let(:subject) { client.create_session.route_to(:ca) } before :each do Puppet[:ca_server] = 'www.example.com' Puppet[:ca_port] = 443 end context 'when making requests' do let(:uri) {"https://www.example.com:443/puppet-ca/v1/certificate/ca"} it 'includes default HTTP headers' do stub_request(:get, uri).with do |request| expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./}) expect(request.headers).to_not include('X-Puppet-Profiling') end subject.get_certificate('ca') end end context 'when routing to the CA service' do let(:cert) { cert_fixture('ca.pem') } let(:pem) { cert.to_pem } it 'defaults the server and port based on settings' do Puppet[:ca_server] = 'ca.example.com' Puppet[:ca_port] = 8141 stub_request(:get, "https://ca.example.com:8141/puppet-ca/v1/certificate/ca").to_return(body: pem) subject.get_certificate('ca') end it 'fallbacks to server and serverport' do Puppet[:ca_server] = nil Puppet[:ca_port] = nil Puppet[:server] = 'ca2.example.com' Puppet[:serverport] = 8142 stub_request(:get, "https://ca2.example.com:8142/puppet-ca/v1/certificate/ca").to_return(body: pem) subject.get_certificate('ca') end end context 'when getting certificates' do let(:cert) { cert_fixture('ca.pem') } let(:pem) { cert.to_pem } let(:url) { "https://www.example.com/puppet-ca/v1/certificate/ca" } it 'includes headers set via the :http_extra_headers and :profile settings' do stub_request(:get, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}) Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing' Puppet[:profile] = true subject.get_certificate('ca') end it 'gets a certificate from the "certificate" endpoint' do stub_request(:get, url).to_return(body: pem) _, body = subject.get_certificate('ca') expect(body).to eq(pem) end it 'returns the request response' do stub_request(:get, url).to_return(body: pem) resp, _ = subject.get_certificate('ca') expect(resp).to be_a(Puppet::HTTP::Response) end it 'accepts text/plain responses' do stub_request(:get, url).with(headers: {'Accept' => 'text/plain'}) subject.get_certificate('ca') end it 'raises a response error if unsuccessful' do stub_request(:get, url).to_return(status: [404, 'Not Found']) expect { subject.get_certificate('ca') }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq("Not Found") expect(err.response.code).to eq(404) end end it 'raises a 304 response error if it is unmodified' do stub_request(:get, url).to_return(status: [304, 'Not Modified']) expect { subject.get_certificate('ca', if_modified_since: Time.now) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq("Not Modified") expect(err.response.code).to eq(304) end end end context 'when getting CRLs' do let(:crl) { crl_fixture('crl.pem') } let(:pem) { crl.to_pem } let(:url) { "https://www.example.com/puppet-ca/v1/certificate_revocation_list/ca" } it 'includes headers set via the :http_extra_headers and :profile settings' do stub_request(:get, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}) Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing' Puppet[:profile] = true subject.get_certificate_revocation_list end it 'gets a CRL from "certificate_revocation_list" endpoint' do stub_request(:get, url).to_return(body: pem) _, body = subject.get_certificate_revocation_list expect(body).to eq(pem) end it 'returns the request response' do stub_request(:get, url).to_return(body: pem) resp, _ = subject.get_certificate_revocation_list expect(resp).to be_a(Puppet::HTTP::Response) end it 'accepts text/plain responses' do stub_request(:get, url).with(headers: {'Accept' => 'text/plain'}) subject.get_certificate_revocation_list end it 'raises a response error if unsuccessful' do stub_request(:get, url).to_return(status: [404, 'Not Found']) expect { subject.get_certificate_revocation_list }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq("Not Found") expect(err.response.code).to eq(404) end end it 'raises a 304 response error if it is unmodified' do stub_request(:get, url).to_return(status: [304, 'Not Modified']) expect { subject.get_certificate_revocation_list(if_modified_since: Time.now) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq("Not Modified") expect(err.response.code).to eq(304) end end end context 'when submitting a CSR' do let(:request) { request_fixture('request.pem') } let(:pem) { request.to_pem } let(:url) { "https://www.example.com/puppet-ca/v1/certificate_request/infinity" } it 'includes headers set via the :http_extra_headers and :profile settings' do stub_request(:put, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}) Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing' Puppet[:profile] = true subject.put_certificate_request('infinity', request) end it 'submits a CSR to the "certificate_request" endpoint' do stub_request(:put, url).with(body: pem, headers: { 'Content-Type' => 'text/plain' }) subject.put_certificate_request('infinity', request) end it 'returns the request response' do stub_request(:put, url).with(body: pem, headers: { 'Content-Type' => 'text/plain' }) resp = subject.put_certificate_request('infinity', request) expect(resp).to be_a(Puppet::HTTP::Response) end it 'raises response error if unsuccessful' do stub_request(:put, url).to_return(status: [400, 'Bad Request']) expect { subject.put_certificate_request('infinity', request) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Bad Request') expect(err.response.code).to eq(400) end end end context 'when getting certificates' do let(:cert) { cert_fixture('signed.pem') } let(:pem) { cert.to_pem } let(:url) { "https://www.example.com/puppet-ca/v1/certificate_renewal" } let(:cert_context) { Puppet::SSL::SSLContext.new(client_cert: pem) } let(:client) { Puppet::HTTP::Client.new(ssl_context: cert_context) } let(:session) { Puppet::HTTP::Session.new(client, []) } let(:subject) { client.create_session.route_to(:ca) } it "gets a certificate from the 'certificate_renewal' endpoint" do stub_request(:post, url).to_return(body: pem) _, body = subject.post_certificate_renewal(cert_context) expect(body).to eq(pem) end it 'returns the request response' do stub_request(:post, url).to_return(body: 'pem') resp, _ = subject.post_certificate_renewal(cert_context) expect(resp).to be_a(Puppet::HTTP::Response) end it 'accepts text/plain responses' do stub_request(:post, url).with(headers: {'Accept' => 'text/plain'}) subject.post_certificate_renewal(cert_context) end it 'raises an ArgumentError if the SSL context does not contain a client cert' do stub_request(:post, url) expect { subject.post_certificate_renewal(ssl_context) }.to raise_error(ArgumentError, 'SSL context must contain a client certificate.') end it 'raises response error if unsuccessful' do stub_request(:post, url).to_return(status: [400, 'Bad Request']) expect { subject.post_certificate_renewal(cert_context) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Bad Request') expect(err.response.code).to eq(400) end end it 'raises a response error if unsuccessful' do stub_request(:post, url).to_return(status: [404, 'Not Found']) expect { subject.post_certificate_renewal(cert_context) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq("Not Found") expect(err.response.code).to eq(404) end end it 'raises a response error if unsuccessful' do stub_request(:post, url).to_return(status: [404, 'Forbidden']) expect { subject.post_certificate_renewal(cert_context) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq("Forbidden") expect(err.response.code).to eq(404) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/service/puppetserver_spec.rb
spec/unit/http/service/puppetserver_spec.rb
require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::Service::Puppetserver do let(:ssl_context) { Puppet::SSL::SSLContext.new } let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) } let(:subject) { client.create_session.route_to(:puppetserver) } before :each do Puppet[:server] = 'puppetserver.example.com' end context 'when making requests' do it 'includes default HTTP headers' do stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/server").with do |request| expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./}) expect(request.headers).to_not include('X-Puppet-Profiling') end.to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'}) subject.get_simple_status end it 'includes extra headers' do Puppet[:http_extra_headers] = 'region:us-west' stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/server") .with(headers: {'Region' => 'us-west'}) .to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'}) subject.get_simple_status end end context 'when routing to the puppetserver service' do it 'defaults the server and port based on settings' do Puppet[:server] = 'compiler2.example.com' Puppet[:serverport] = 8141 stub_request(:get, "https://compiler2.example.com:8141/status/v1/simple/server") .to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'}) subject.get_simple_status end end context 'when getting puppetserver status' do let(:url) { "https://puppetserver.example.com:8140/status/v1/simple/server" } it 'returns the request response and status' do stub_request(:get, url) .to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'}) resp, status = subject.get_simple_status expect(resp).to be_a(Puppet::HTTP::Response) expect(status).to eq('running') end it 'raises a response error if unsuccessful' do stub_request(:get, url).to_return(status: [500, 'Internal Server Error']) expect { subject.get_simple_status }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq("Internal Server Error") expect(err.response.code).to eq(500) end end it 'accepts an ssl context' do stub_request(:get, url) .to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'}) other_ctx = Puppet::SSL::SSLContext.new expect(client).to receive(:connect).with(URI(url), options: {ssl_context: other_ctx}).and_call_original session = client.create_session service = Puppet::HTTP::Service.create_service(client, session, :puppetserver, 'puppetserver.example.com', 8140) service.get_simple_status(ssl_context: other_ctx) end end context 'when /status/v1/simple/server returns not found' do it 'calls /status/v1/simple/master' do stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/server") .to_return(status: [404, 'not found: server']) stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/master") .to_return(body: "running", headers: {'Content-Type' => 'text/plain;charset=utf-8'}) resp, status = subject.get_simple_status expect(resp).to be_a(Puppet::HTTP::Response) expect(status).to eq('running') end it 'raises a response error if fallback is unsuccessful' do stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/server") .to_return(status: [404, 'not found: server']) stub_request(:get, "https://puppetserver.example.com:8140/status/v1/simple/master") .to_return(status: [404, 'not found: master']) expect { subject.get_simple_status }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('not found: master') expect(err.response.code).to eq(404) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/service/report_spec.rb
spec/unit/http/service/report_spec.rb
require 'spec_helper' require 'puppet_spec/network' require 'puppet/http' describe Puppet::HTTP::Service::Report do include PuppetSpec::Network let(:ssl_context) { Puppet::SSL::SSLContext.new } let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) } let(:subject) { client.create_session.route_to(:report) } let(:environment) { 'testing' } let(:report) { Puppet::Transaction::Report.new } before :each do Puppet[:report_server] = 'www.example.com' Puppet[:report_port] = 443 end context 'when making requests' do let(:uri) {"https://www.example.com:443/puppet/v3/report/report?environment=testing"} it 'includes default HTTP headers' do stub_request(:put, uri).with do |request| expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./}) expect(request.headers).to_not include('X-Puppet-Profiling') end subject.put_report('report', report, environment: environment) end end context 'when routing to the report service' do it 'defaults the server and port based on settings' do Puppet[:report_server] = 'report.example.com' Puppet[:report_port] = 8141 stub_request(:put, "https://report.example.com:8141/puppet/v3/report/report?environment=testing") subject.put_report('report', report, environment: environment) end it 'fallbacks to server and serverport' do Puppet[:report_server] = nil Puppet[:report_port] = nil Puppet[:server] = 'report2.example.com' Puppet[:serverport] = 8142 stub_request(:put, "https://report2.example.com:8142/puppet/v3/report/report?environment=testing") subject.put_report('report', report, environment: environment) end end context 'when submitting a report' do let(:url) { "https://www.example.com/puppet/v3/report/infinity?environment=testing" } it 'includes puppet headers set via the :http_extra_headers and :profile settings' do stub_request(:put, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}) Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing' Puppet[:profile] = true subject.put_report('infinity', report, environment: environment) end it 'submits a report to the "report" endpoint' do stub_request(:put, url) .with( headers: { 'Accept'=>acceptable_content_types_string, 'Content-Type'=>'application/json', }). to_return(status: 200, body: "", headers: {}) subject.put_report('infinity', report, environment: environment) end it 'percent encodes the uri before submitting the report' do stub_request(:put, "https://www.example.com/puppet/v3/report/node%20name?environment=testing") .to_return(status: 200, body: "", headers: {}) subject.put_report('node name', report, environment: environment) end it 'returns the response whose body contains the list of report processors' do body = "[\"store\":\"http\"]" stub_request(:put, url) .to_return(status: 200, body: body, headers: {'Content-Type' => 'application/json'}) resp = subject.put_report('infinity', report, environment: environment) expect(resp.body).to eq(body) expect(resp).to be_a(Puppet::HTTP::Response) end it 'raises response error if unsuccessful' do stub_request(:put, url).to_return(status: [400, 'Bad Request'], headers: {'X-Puppet-Version' => '6.1.8' }) expect { subject.put_report('infinity', report, environment: environment) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Bad Request') expect(err.response.code).to eq(400) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/service/file_server_spec.rb
spec/unit/http/service/file_server_spec.rb
require 'spec_helper' require 'puppet_spec/network' require 'puppet/http' describe Puppet::HTTP::Service::FileServer do include PuppetSpec::Files include PuppetSpec::Network let(:ssl_context) { Puppet::SSL::SSLContext.new } let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) } let(:subject) { client.create_session.route_to(:fileserver) } let(:environment) { 'testing' } let(:report) { Puppet::Transaction::Report.new } before :each do Puppet[:server] = 'www.example.com' Puppet[:serverport] = 443 end context 'when making requests' do let(:uri) {"https://www.example.com:443/puppet/v3/file_content/:mount/:path?environment=testing"} it 'includes default HTTP headers' do stub_request(:get, uri).with do |request| expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./}) expect(request.headers).to_not include('X-Puppet-Profiling') end subject.get_file_content(path: '/:mount/:path', environment: environment) { |data| } end end context 'when routing to the file service' do it 'defaults the server and port based on settings' do Puppet[:server] = 'file.example.com' Puppet[:serverport] = 8141 stub_request(:get, "https://file.example.com:8141/puppet/v3/file_content/:mount/:path?environment=testing") subject.get_file_content(path: '/:mount/:path', environment: environment) { |data| } end end context 'retrieving file metadata' do let(:path) { tmpfile('get_file_metadata') } let(:url) { "https://www.example.com/puppet/v3/file_metadata/:mount/#{path}?checksum_type=sha256&environment=testing&links=manage&source_permissions=ignore" } let(:filemetadata) { Puppet::FileServing::Metadata.new(path) } let(:request_path) { "/:mount/#{path}"} it 'includes puppet headers set via the :http_extra_headers and :profile settings' do stub_request(:get, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}). to_return(status: 200, body: filemetadata.render, headers: { 'Content-Type' => 'application/json' }) Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing' Puppet[:profile] = true subject.get_file_metadata(path: request_path, environment: environment) end it 'submits a request for file metadata to the server' do stub_request(:get, url).with( headers: {'Accept'=>acceptable_content_types_string} ).to_return( status: 200, body: filemetadata.render, headers: { 'Content-Type' => 'application/json' } ) _, metadata = subject.get_file_metadata(path: request_path, environment: environment) expect(metadata.path).to eq(path) end it 'returns the request response' do stub_request(:get, url).to_return( status: 200, body: filemetadata.render, headers: { 'Content-Type' => 'application/json' } ) resp, _ = subject.get_file_metadata(path: request_path, environment: environment) expect(resp).to be_a(Puppet::HTTP::Response) end it 'raises a protocol error if the Content-Type header is missing from the response' do stub_request(:get, url).to_return(status: 200, body: '', headers: {}) expect { subject.get_file_metadata(path: request_path, environment: environment) }.to raise_error(Puppet::HTTP::ProtocolError, "No content type in http response; cannot parse") end it 'raises an error if the Content-Type is unsupported' do stub_request(:get, url).to_return(status: 200, body: '', headers: { 'Content-Type' => 'text/yaml' }) expect { subject.get_file_metadata(path: request_path, environment: environment) }.to raise_error(Puppet::HTTP::ProtocolError, "Content-Type is unsupported") end it 'raises response error if unsuccessful' do stub_request(:get, url).to_return(status: [400, 'Bad Request']) expect { subject.get_file_metadata(path: request_path, environment: environment) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Bad Request') expect(err.response.code).to eq(400) end end it 'raises a serialization error if serialization fails' do stub_request(:get, url).to_return( status: 200, body: '', headers: { 'Content-Type' => 'application/json' } ) expect { subject.get_file_metadata(path: request_path, environment: environment) }.to raise_error(Puppet::HTTP::SerializationError, /Failed to deserialize Puppet::FileServing::Metadata from json/) end it 'raises response error if path is relative' do expect { subject.get_file_metadata(path: 'relative_path', environment: environment) }.to raise_error(ArgumentError, 'Path must start with a slash') end end context 'retrieving multiple file metadatas' do let(:path) { tmpfile('get_file_metadatas') } let(:url) { "https://www.example.com/puppet/v3/file_metadatas/:mount/#{path}?checksum_type=sha256&links=manage&recurse=false&source_permissions=ignore&environment=testing" } let(:filemetadatas) { [Puppet::FileServing::Metadata.new(path)] } let(:formatter) { Puppet::Network::FormatHandler.format(:json) } let(:request_path) { "/:mount/#{path}"} it 'includes puppet headers set via the :http_extra_headers and :profile settings' do stub_request(:get, url).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}). to_return(status: 200, body: formatter.render_multiple(filemetadatas), headers: { 'Content-Type' => 'application/json' }) Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing' Puppet[:profile] = true subject.get_file_metadatas(path: request_path, environment: environment) end it 'submits a request for file metadata to the server' do stub_request(:get, url).with( headers: {'Accept' => acceptable_content_types_string} ).to_return( status: 200, body: formatter.render_multiple(filemetadatas), headers: { 'Content-Type' => 'application/json' } ) _, metadatas = subject.get_file_metadatas(path: request_path, environment: environment) expect(metadatas.first.path).to eq(path) end it 'returns the request response' do stub_request(:get, url).to_return( status: 200, body: formatter.render_multiple(filemetadatas), headers: { 'Content-Type' => 'application/json' } ) resp, _ = subject.get_file_metadatas(path: request_path, environment: environment) expect(resp).to be_a(Puppet::HTTP::Response) end it 'automatically converts an array of parameters to the stringified query' do url = "https://www.example.com/puppet/v3/file_metadatas/:mount/#{path}?checksum_type=sha256&environment=testing&ignore=CVS&ignore=.git&ignore=.hg&links=manage&recurse=false&source_permissions=ignore" stub_request(:get, url).with( headers: {'Accept'=>acceptable_content_types_string} ).to_return( status: 200, body: formatter.render_multiple(filemetadatas), headers: { 'Content-Type' => 'application/json' } ) _, metadatas = subject.get_file_metadatas(path: request_path, environment: environment, ignore: ['CVS', '.git', '.hg']) expect(metadatas.first.path).to eq(path) end it 'raises a protocol error if the Content-Type header is missing from the response' do stub_request(:get, url).to_return(status: 200, body: '', headers: {}) expect { subject.get_file_metadatas(path: request_path, environment: environment) }.to raise_error(Puppet::HTTP::ProtocolError, "No content type in http response; cannot parse") end it 'raises an error if the Content-Type is unsupported' do stub_request(:get, url).to_return(status: 200, body: '', headers: { 'Content-Type' => 'text/yaml' }) expect { subject.get_file_metadatas(path: request_path, environment: environment) }.to raise_error(Puppet::HTTP::ProtocolError, "Content-Type is unsupported") end it 'raises response error if unsuccessful' do stub_request(:get, url).to_return(status: [400, 'Bad Request']) expect { subject.get_file_metadatas(path: request_path, environment: environment) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Bad Request') expect(err.response.code).to eq(400) end end it 'raises a serialization error if serialization fails' do stub_request(:get, url).to_return( status: 200, body: '', headers: { 'Content-Type' => 'application/json' } ) expect { subject.get_file_metadatas(path: request_path, environment: environment) }.to raise_error(Puppet::HTTP::SerializationError, /Failed to deserialize multiple Puppet::FileServing::Metadata from json/) end it 'raises response error if path is relative' do expect { subject.get_file_metadatas(path: 'relative_path', environment: environment) }.to raise_error(ArgumentError, 'Path must start with a slash') end end context 'getting file content' do let(:uri) {"https://www.example.com:443/puppet/v3/file_content/:mount/:path?environment=testing"} it 'includes puppet headers set via the :http_extra_headers and :profile settings' do stub_request(:get, uri).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}). to_return(status: 200, body: "and beyond") Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing' Puppet[:profile] = true expect { |b| subject.get_file_content(path: '/:mount/:path', environment: environment, &b) }.to yield_with_args("and beyond") end it 'yields file content' do stub_request(:get, uri).with do |request| expect(request.headers).to include({'Accept' => 'application/octet-stream'}) end.to_return(status: 200, body: "and beyond") expect { |b| subject.get_file_content(path: '/:mount/:path', environment: environment, &b) }.to yield_with_args("and beyond") end it 'returns the request response' do stub_request(:get, uri) resp = subject.get_file_content(path: '/:mount/:path', environment: environment) { |b| b } expect(resp).to be_a(Puppet::HTTP::Response) end it 'raises response error if unsuccessful' do stub_request(:get, uri).to_return(status: [400, 'Bad Request']) expect { subject.get_file_content(path: '/:mount/:path', environment: environment) { |data| } }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Bad Request') expect(err.response.code).to eq(400) end end it 'raises response error if path is relative' do expect { subject.get_file_content(path: 'relative_path', environment: environment) { |data| } }.to raise_error(ArgumentError, 'Path must start with a slash') end end context 'getting static file content' do let(:code_id) { "0fc72115-adc6-4b1a-aa50-8f31b3ece440" } let(:uri) { "https://www.example.com:443/puppet/v3/static_file_content/:mount/:path?environment=testing&code_id=#{code_id}"} it 'yields file content' do stub_request(:get, uri).with do |request| expect(request.headers).to include({'Accept' => 'application/octet-stream'}) end.to_return(status: 200, body: "and beyond") expect { |b| subject.get_static_file_content(path: '/:mount/:path', environment: environment, code_id: code_id, &b) }.to yield_with_args("and beyond") end it 'returns the request response' do stub_request(:get, uri) resp = subject.get_static_file_content(path: '/:mount/:path', environment: environment, code_id: code_id) { |b| b } expect(resp).to be_a(Puppet::HTTP::Response) end it 'raises response error if unsuccessful' do stub_request(:get, uri).to_return(status: [400, 'Bad Request']) expect { subject.get_static_file_content(path: '/:mount/:path', environment: environment, code_id: code_id) { |data| } }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Bad Request') expect(err.response.code).to eq(400) end end it 'raises response error if path is relative' do expect { subject.get_static_file_content(path: 'relative_path', environment: environment, code_id: code_id) { |data| } }.to raise_error(ArgumentError, 'Path must start with a slash') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/http/service/compiler_spec.rb
spec/unit/http/service/compiler_spec.rb
# coding: utf-8 require 'spec_helper' require 'puppet/http' describe Puppet::HTTP::Service::Compiler do let(:ssl_context) { Puppet::SSL::SSLContext.new } let(:client) { Puppet::HTTP::Client.new(ssl_context: ssl_context) } let(:subject) { client.create_session.route_to(:puppet) } let(:environment) { 'testing' } let(:certname) { 'ziggy' } let(:node) { Puppet::Node.new(certname) } let(:facts) { Puppet::Node::Facts.new(certname) } let(:catalog) { Puppet::Resource::Catalog.new(certname) } let(:formatter) { Puppet::Network::FormatHandler.format(:json) } before :each do Puppet[:server] = 'compiler.example.com' Puppet[:serverport] = 8140 Puppet::Node::Facts.indirection.terminus_class = :memory end context 'when making requests' do let(:uri) {"https://compiler.example.com:8140/puppet/v3/catalog/ziggy?environment=testing"} it 'includes default HTTP headers' do stub_request(:post, uri).with do |request| expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./}) expect(request.headers).to_not include('X-Puppet-Profiling') end.to_return(body: formatter.render(catalog), headers: {'Content-Type' => formatter.mime }) subject.post_catalog(certname, environment: environment, facts: facts) end end context 'when routing to the compiler service' do it 'defaults the server and port based on settings' do Puppet[:server] = 'compiler2.example.com' Puppet[:serverport] = 8141 stub_request(:post, "https://compiler2.example.com:8141/puppet/v3/catalog/ziggy?environment=testing") .to_return(body: formatter.render(catalog), headers: {'Content-Type' => formatter.mime }) subject.post_catalog(certname, environment: environment, facts: facts) end end context 'when posting for a catalog' do let(:uri) { %r{/puppet/v3/catalog/ziggy} } let(:catalog_response) { { body: formatter.render(catalog), headers: {'Content-Type' => formatter.mime } } } it 'includes puppet headers set via the :http_extra_headers and :profile settings' do stub_request(:post, uri).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}). to_return(body: formatter.render(catalog), headers: {'Content-Type' => formatter.mime }) Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing' Puppet[:profile] = true subject.post_catalog(certname, environment: environment, facts: facts) end it 'submits facts as application/json by default' do stub_request(:post, uri) .with(body: hash_including("facts_format" => /application\/json/)) .to_return(**catalog_response) subject.post_catalog(certname, environment: environment, facts: facts) end it 'submits facts as pson if set as the preferred format', if: Puppet.features.pson? do Puppet[:preferred_serialization_format] = "pson" stub_request(:post, uri) .with(body: hash_including("facts_format" => /pson/)) .to_return(**catalog_response) subject.post_catalog(certname, environment: environment, facts: facts) end it 'includes environment as a query parameter AND in the POST body' do stub_request(:post, uri) .with(query: {"environment" => "outerspace"}, body: hash_including("environment" => 'outerspace')) .to_return(**catalog_response) subject.post_catalog(certname, environment: 'outerspace', facts: facts) end it 'includes configured_environment' do stub_request(:post, uri) .with(body: hash_including("configured_environment" => 'agent_specified')) .to_return(**catalog_response) subject.post_catalog(certname, environment: 'production', facts: facts, configured_environment: 'agent_specified') end it 'includes check_environment' do stub_request(:post, uri) .with(body: hash_including('check_environment' => 'false')) .to_return(**catalog_response) subject.post_catalog(certname, environment: 'production', facts: facts) end it 'includes transaction_uuid' do uuid = "ec3d2844-b236-4287-b0ad-632fbb4d1ff0" stub_request(:post, uri) .with(body: hash_including("transaction_uuid" => uuid)) .to_return(**catalog_response) subject.post_catalog(certname, environment: 'production', facts: facts, transaction_uuid: uuid) end it 'includes job_uuid' do uuid = "3dd13eec-1b6b-4b5d-867b-148193e0593e" stub_request(:post, uri) .with(body: hash_including("job_uuid" => uuid)) .to_return(**catalog_response) subject.post_catalog(certname, environment: 'production', facts: facts, job_uuid: uuid) end it 'includes static_catalog' do stub_request(:post, uri) .with(body: hash_including("static_catalog" => "false")) .to_return(**catalog_response) subject.post_catalog(certname, environment: 'production', facts: facts, static_catalog: false) end it 'includes dot-separated list of checksum_types' do stub_request(:post, uri) .with(body: hash_including("checksum_type" => "sha256.sha384")) .to_return(**catalog_response) subject.post_catalog(certname, environment: 'production', facts: facts, checksum_type: %w[sha256 sha384]) end it 'does not accept msgpack by default' do stub_request(:post, uri) .with(headers: {'Accept' => 'application/vnd.puppet.rich+json, application/json'}) .to_return(**catalog_response) allow(Puppet.features).to receive(:msgpack?).and_return(false) allow(Puppet.features).to receive(:pson?).and_return(false) subject.post_catalog(certname, environment: environment, facts: facts) end it 'accepts msgpack & rich_json_msgpack if the gem is present' do stub_request(:post, uri) .with(headers: {'Accept' => 'application/vnd.puppet.rich+json, application/json, application/vnd.puppet.rich+msgpack, application/x-msgpack'}) .to_return(**catalog_response) allow(Puppet.features).to receive(:msgpack?).and_return(true) allow(Puppet.features).to receive(:pson?).and_return(false) subject.post_catalog(certname, environment: environment, facts: facts) end it 'returns a deserialized catalog' do stub_request(:post, uri) .to_return(**catalog_response) _, cat = subject.post_catalog(certname, environment: 'production', facts: facts) expect(cat).to be_a(Puppet::Resource::Catalog) expect(cat.name).to eq(certname) end it 'deserializes the catalog from msgpack', if: Puppet.features.msgpack? do body = catalog.to_msgpack formatter = Puppet::Network::FormatHandler.format(:msgpack) catalog_response = { body: body, headers: {'Content-Type' => formatter.mime }} stub_request(:post, uri) .to_return(**catalog_response) _, cat = subject.post_catalog(certname, environment: 'production', facts: facts) expect(cat).to be_a(Puppet::Resource::Catalog) expect(cat.name).to eq(certname) end it 'deserializes the catalog from rich msgpack', if: Puppet.features.msgpack? do body = Puppet.override(rich_data: true) do catalog.to_msgpack end formatter = Puppet::Network::FormatHandler.format(:rich_data_msgpack) catalog_response = { body: body, headers: {'Content-Type' => formatter.mime }} stub_request(:post, uri) .to_return(**catalog_response) _, cat = subject.post_catalog(certname, environment: 'production', facts: facts) expect(cat).to be_a(Puppet::Resource::Catalog) expect(cat.name).to eq(certname) end it 'returns the request response' do stub_request(:post, uri) .to_return(**catalog_response) resp, _ = subject.post_catalog(certname, environment: 'production', facts: facts) expect(resp).to be_a(Puppet::HTTP::Response) end it 'raises a response error if unsuccessful' do stub_request(:post, uri) .to_return(status: [500, "Server Error"]) expect { subject.post_catalog(certname, environment: 'production', facts: facts) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Server Error') expect(err.response.code).to eq(500) end end it 'raises a protocol error if the content-type header is missing' do stub_request(:post, uri) .to_return(body: "content-type is missing") expect { subject.post_catalog(certname, environment: 'production', facts: facts) }.to raise_error(Puppet::HTTP::ProtocolError, /No content type in http response; cannot parse/) end it 'raises a serialization error if the content is invalid' do stub_request(:post, uri) .to_return(body: "this isn't valid JSON", headers: {'Content-Type' => 'application/json'}) expect { subject.post_catalog(certname, environment: 'production', facts: facts) }.to raise_error(Puppet::HTTP::SerializationError, /Failed to deserialize Puppet::Resource::Catalog from json/) end context 'serializing facts' do facts_with_special_characters = [ { :hash => { 'afact' => 'a+b' }, :encoded => 'a%2Bb' }, { :hash => { 'afact' => 'a b' }, :encoded => 'a%20b' }, { :hash => { 'afact' => 'a&b' }, :encoded => 'a%26b' }, { :hash => { 'afact' => 'a*b' }, :encoded => 'a%2Ab' }, { :hash => { 'afact' => 'a=b' }, :encoded => 'a%3Db' }, # different UTF-8 widths # 1-byte A # 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191 # 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160 # 4-byte 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142 { :hash => { 'afact' => "A\u06FF\u16A0\u{2070E}" }, :encoded => 'A%DB%BF%E1%9A%A0%F0%A0%9C%8E' }, ] facts_with_special_characters.each do |test_fact| it "escapes special characters #{test_fact[:hash]}" do facts = Puppet::Node::Facts.new(certname, test_fact[:hash]) Puppet::Node::Facts.indirection.save(facts) stub_request(:post, uri) .with(body: hash_including("facts" => /#{test_fact[:encoded]}/)) .to_return(**catalog_response) subject.post_catalog(certname, environment: environment, facts: facts) end end end end context 'when posting for a v4 catalog' do let(:uri) {"https://compiler.example.com:8140/puppet/v4/catalog"} let(:persistence) {{ facts: true, catalog: true }} let(:facts) {{ 'foo' => 'bar' }} let(:trusted_facts) {{}} let(:uuid) { "ec3d2844-b236-4287-b0ad-632fbb4d1ff0" } let(:job_id) { "1" } let(:payload) {{ environment: environment, persistence: persistence, facts: facts, trusted_facts: trusted_facts, transaction_uuid: uuid, job_id: job_id, options: { prefer_requested_environment: false, capture_logs: false } }} let(:serialized_catalog) {{ 'catalog' => catalog.to_data_hash }.to_json} let(:catalog_response) {{ body: serialized_catalog, headers: {'Content-Type' => formatter.mime }}} it 'includes default HTTP headers' do stub_request(:post, uri).with do |request| expect(request.headers).to include({'X-Puppet-Version' => /./, 'User-Agent' => /./}) expect(request.headers).to_not include('X-Puppet-Profiling') end.to_return(**catalog_response) subject.post_catalog4(certname, **payload) end it 'defaults the server and port based on settings' do Puppet[:server] = 'compiler2.example.com' Puppet[:serverport] = 8141 stub_request(:post, "https://compiler2.example.com:8141/puppet/v4/catalog") .to_return(**catalog_response) subject.post_catalog4(certname, **payload) end it 'includes puppet headers set via the :http_extra_headers and :profile settings' do stub_request(:post, uri).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}). to_return(**catalog_response) Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing' Puppet[:profile] = true subject.post_catalog4(certname, **payload) end it 'returns a deserialized catalog' do stub_request(:post, uri) .to_return(**catalog_response) _, cat, _ = subject.post_catalog4(certname, **payload) expect(cat).to be_a(Puppet::Resource::Catalog) expect(cat.name).to eq(certname) end it 'returns the request response' do stub_request(:post, uri) .to_return(**catalog_response) resp, _, _ = subject.post_catalog4(certname, **payload) expect(resp).to be_a(Puppet::HTTP::Response) end it 'raises a response error if unsuccessful' do stub_request(:post, uri) .to_return(status: [500, "Server Error"]) expect { subject.post_catalog4(certname, **payload) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Server Error') expect(err.response.code).to eq(500) end end it 'raises a response error when server response is not JSON' do stub_request(:post, uri) .to_return(body: "this isn't valid JSON", headers: {'Content-Type' => 'application/json'}) expect { subject.post_catalog4(certname, **payload) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::SerializationError) expect(err.message).to match(/Failed to deserialize catalog from puppetserver response/) end end it 'raises a response error when server response a JSON serialized catalog' do stub_request(:post, uri) .to_return(body: {oops: 'bad response data'}.to_json, headers: {'Content-Type' => 'application/json'}) expect { subject.post_catalog4(certname, **payload) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::SerializationError) expect(err.message).to match(/Failed to deserialize catalog from puppetserver response/) end end it 'raises ArgumentError when the `persistence` hash does not contain required keys' do payload[:persistence].delete(:facts) expect { subject.post_catalog4(certname, **payload) }.to raise_error do |err| expect(err).to be_an_instance_of(ArgumentError) expect(err.message).to match(/The 'persistence' hash is missing the keys: facts/) end end it 'raises ArgumentError when `facts` are not a Hash' do payload[:facts] = Puppet::Node::Facts.new(certname) expect { subject.post_catalog4(certname, **payload) }.to raise_error do |err| expect(err).to be_an_instance_of(ArgumentError) expect(err.message).to match(/Facts must be a Hash not a Puppet::Node::Facts/) end end end context 'when getting a node' do let(:uri) { %r{/puppet/v3/node/ziggy} } let(:node_response) { { body: formatter.render(node), headers: {'Content-Type' => formatter.mime } } } it 'includes custom headers set via the :http_extra_headers and :profile settings' do stub_request(:get, uri).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}). to_return(**node_response) Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing' Puppet[:profile] = true subject.get_node(certname, environment: 'production') end it 'includes environment' do stub_request(:get, uri) .with(query: hash_including("environment" => "outerspace")) .to_return(**node_response) subject.get_node(certname, environment: 'outerspace') end it 'includes configured_environment' do stub_request(:get, uri) .with(query: hash_including("configured_environment" => 'agent_specified')) .to_return(**node_response) subject.get_node(certname, environment: 'production', configured_environment: 'agent_specified') end it 'includes transaction_uuid' do uuid = "ec3d2844-b236-4287-b0ad-632fbb4d1ff0" stub_request(:get, uri) .with(query: hash_including("transaction_uuid" => uuid)) .to_return(**node_response) subject.get_node(certname, environment: 'production', transaction_uuid: uuid) end it 'returns a deserialized node' do stub_request(:get, uri) .to_return(**node_response) _, n = subject.get_node(certname, environment: 'production') expect(n).to be_a(Puppet::Node) expect(n.name).to eq(certname) end it 'returns the request response' do stub_request(:get, uri) .to_return(**node_response) resp, _ = subject.get_node(certname, environment: 'production') expect(resp).to be_a(Puppet::HTTP::Response) end it 'raises a response error if unsuccessful' do stub_request(:get, uri) .to_return(status: [500, "Server Error"]) expect { subject.get_node(certname, environment: 'production') }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Server Error') expect(err.response.code).to eq(500) end end it 'raises a protocol error if the content-type header is missing' do stub_request(:get, uri) .to_return(body: "content-type is missing") expect { subject.get_node(certname, environment: 'production') }.to raise_error(Puppet::HTTP::ProtocolError, /No content type in http response; cannot parse/) end it 'raises a serialization error if the content is invalid' do stub_request(:get, uri) .to_return(body: "this isn't valid JSON", headers: {'Content-Type' => 'application/json'}) expect { subject.get_node(certname, environment: 'production') }.to raise_error(Puppet::HTTP::SerializationError, /Failed to deserialize Puppet::Node from json/) end end context 'when getting facts' do let(:uri) { %r{/puppet/v3/facts/ziggy} } let(:facts_response) { { body: formatter.render(facts), headers: {'Content-Type' => formatter.mime } } } it 'includes environment' do stub_request(:get, uri) .with(query: hash_including("environment" => "outerspace")) .to_return(**facts_response) subject.get_facts(certname, environment: 'outerspace') end it 'returns a deserialized facts object' do stub_request(:get, uri) .to_return(**facts_response) _, n = subject.get_facts(certname, environment: 'production') expect(n).to be_a(Puppet::Node::Facts) expect(n.name).to eq(certname) end it 'returns the request response' do stub_request(:get, uri) .to_return(**facts_response) resp, _ = subject.get_facts(certname, environment: 'production') expect(resp).to be_a(Puppet::HTTP::Response) end it 'raises a response error if unsuccessful' do stub_request(:get, uri) .to_return(status: [500, "Server Error"]) expect { subject.get_facts(certname, environment: 'production') }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Server Error') expect(err.response.code).to eq(500) end end it 'raises a protocol error if the content-type header is missing' do stub_request(:get, uri) .to_return(body: "content-type is missing") expect { subject.get_facts(certname, environment: 'production') }.to raise_error(Puppet::HTTP::ProtocolError, /No content type in http response; cannot parse/) end it 'raises a serialization error if the content is invalid' do stub_request(:get, uri) .to_return(body: "this isn't valid JSON", headers: {'Content-Type' => 'application/json'}) expect { subject.get_facts(certname, environment: 'production') }.to raise_error(Puppet::HTTP::SerializationError, /Failed to deserialize Puppet::Node::Facts from json/) end end context 'when putting facts' do let(:uri) { %r{/puppet/v3/facts/ziggy} } it 'includes custom headers set the :http_extra_headers and :profile settings' do stub_request(:put, uri).with(headers: {'Example-Header' => 'real-thing', 'another' => 'thing', 'X-Puppet-Profiling' => 'true'}) Puppet[:http_extra_headers] = 'Example-Header:real-thing,another:thing' Puppet[:profile] = true subject.put_facts(certname, environment: environment, facts: facts) end it 'serializes facts in the body' do facts = Puppet::Node::Facts.new(certname, { 'domain' => 'zork'}) Puppet::Node::Facts.indirection.save(facts) stub_request(:put, uri) .with(body: hash_including("name" => "ziggy", "values" => {"domain" => "zork"})) subject.put_facts(certname, environment: environment, facts: facts) end it 'includes environment' do stub_request(:put, uri) .with(query: {"environment" => "outerspace"}) subject.put_facts(certname, environment: 'outerspace', facts: facts) end it 'returns the request response' do # the REST API returns the filename, good grief stub_request(:put, uri) .to_return(status: 200, body: "/opt/puppetlabs/server/data/puppetserver/yaml/facts/#{certname}.yaml") expect(subject.put_facts(certname, environment: environment, facts: facts)).to be_a(Puppet::HTTP::Response) end it 'raises a response error if unsuccessful' do stub_request(:put, uri) .to_return(status: [500, "Server Error"]) expect { subject.put_facts(certname, environment: environment, facts: facts) }.to raise_error do |err| expect(err).to be_an_instance_of(Puppet::HTTP::ResponseError) expect(err.message).to eq('Server Error') expect(err.response.code).to eq(500) end end it 'raises a serialization error if the report cannot be serialized' do invalid_facts = Puppet::Node::Facts.new(certname, {'invalid_utf8_sequence' => "\xE2\x82".force_encoding('binary')}) expect { subject.put_facts(certname, environment: 'production', facts: invalid_facts) }.to raise_error(Puppet::HTTP::SerializationError, /Failed to serialize Puppet::Node::Facts to json: /) end end context 'filebucket' do let(:filebucket_file) { Puppet::FileBucket::File.new('file to store') } let(:formatter) { Puppet::Network::FormatHandler.format(:binary) } let(:path) { "md5/4aabe1257043bd03ce4c3319c155bc55" } let(:uri) { %r{/puppet/v3/file_bucket_file/#{path}} } context 'when getting a file' do let(:status_response) { { body: formatter.render(filebucket_file), headers: {'Content-Type' => 'application/octet-stream' }}} it 'includes default HTTP headers' do stub_request(:get, uri).with do |request| expect(request.headers).to include({ 'X-Puppet-Version' => /./, 'User-Agent' => /./, 'Accept' => 'application/octet-stream' }) expect(request.headers).to_not include('X-Puppet-Profiling') end.to_return(**status_response) subject.get_filebucket_file(path, environment: 'production') end it 'always the environment as a parameter' do stub_request(:get, uri).with(query: hash_including('environment' => 'production')).to_return(**status_response) subject.get_filebucket_file(path, environment: 'production') end {bucket_path: 'path', diff_with: '4aabe1257043bd0', list_all: 'true', fromdate: '20200404', todate: '20200404'}.each do |param, val| it "includes #{param} as a parameter in the request if #{param} is set" do stub_request(:get, uri).with(query: hash_including(param => val)).to_return(**status_response) options = { param => val } subject.get_filebucket_file(path, environment: 'production', **options) end end it "doesn't include :diff_with as a query param if :bucket_path is nil" do stub_request(:get, uri).with do |request| expect(request.uri.query).not_to match(/diff_with/) end.to_return(**status_response) subject.get_filebucket_file(path, environment: 'production', diff_with: nil) end it 'returns a deserialized response' do stub_request(:get, uri) .to_return(**status_response) _, s = subject.get_filebucket_file(path, environment: 'production') expect(s).to be_a(Puppet::FileBucket::File) expect(s.contents).to eq('file to store') end it 'returns the request response' do stub_request(:get, uri) .to_return(**status_response) resp, _ = subject.get_filebucket_file(path, environment: 'production') expect(resp).to be_a(Puppet::HTTP::Response) end end context 'when putting a file' do let(:status_response) { { status: 200, body: '' } } it 'includes default HTTP headers' do stub_request(:put, uri).with do |request| expect(request.headers).to include({ 'X-Puppet-Version' => /./, 'User-Agent' => /./, 'Accept' => 'application/octet-stream', 'Content-Type' => 'application/octet-stream' }) expect(request.headers).to_not include('X-Puppet-Profiling') end.to_return(**status_response) subject.put_filebucket_file(path, body: filebucket_file.contents, environment: 'production') end it 'always the environment as a parameter' do stub_request(:put, uri).with(query: hash_including('environment' => 'production')).to_return(**status_response) subject.put_filebucket_file(path, body: filebucket_file.contents, environment: 'production') end it 'sends the file contents as the request body' do stub_request(:put, uri).with(body: filebucket_file.contents).to_return(**status_response) subject.put_filebucket_file(path, body: filebucket_file.contents, environment: 'production') end it 'returns the request response' do stub_request(:put, uri) .to_return(**status_response) s = subject.put_filebucket_file(path, body: filebucket_file.contents, environment: 'production') expect(s).to be_a(Puppet::HTTP::Response) end end context 'when heading a file' do let(:status_response) {{ status: 200 }} it 'includes default HTTP headers' do stub_request(:head, uri).with do |request| expect(request.headers).to include({ 'X-Puppet-Version' => /./, 'User-Agent' => /./, 'Accept' => 'application/octet-stream', }) expect(request.headers).to_not include('X-Puppet-Profiling') end.to_return(**status_response) subject.head_filebucket_file(path, environment: 'production') end it 'always the environment as a parameter' do stub_request(:head, uri).with(query: hash_including('environment' => 'production')).to_return(**status_response) subject.head_filebucket_file(path, environment: 'production') end it "includes :bucket_path as a parameter in the request if :bucket_path is set" do stub_request(:head, uri).with(query: hash_including(:bucket_path => 'some/path')).to_return(**status_response) subject.head_filebucket_file(path, environment: 'production', bucket_path: 'some/path') end it "doesn't include :bucket_path as a query param if :bucket_path is nil" do stub_request(:head, uri).with do |request| expect(request.uri.query).not_to match(/bucket_path/) end.to_return(**status_response) subject.head_filebucket_file(path, environment: 'production', bucket_path: nil) end it "returns the request response" do stub_request(:head, uri).with(query: hash_including(:bucket_path => 'some/path')).to_return(**status_response) resp = subject.head_filebucket_file(path, environment: 'production', bucket_path: 'some/path') expect(resp).to be_a(Puppet::HTTP::Response) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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/PredicatePrefix 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/PredicatePrefix # 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/PredicatePrefix @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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 attributes = attr.collect { |k| v = parameters[k] " %-#{attr_max}s: %s\n" % [k, Puppet::Parameter.format_value_for_display(v)] }.join " %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 attributes = attr.collect { |k| v = parameters[k] " %-#{attr_max}s => %s,\n" % [k, Puppet::Parameter.format_value_for_display(v)] }.join 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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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.24.2' IMPLEMENTATION = 'openvox' ## # 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 def self.implementation IMPLEMENTATION 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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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/dependency' require_relative 'module_tool/metadata' require_relative '../puppet/forge/cache' require_relative '../puppet/forge'
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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/PredicatePrefix 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/PredicatePrefix # 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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/concurrent.rb
lib/puppet/concurrent.rb
# frozen_string_literal: true module Puppet::Concurrent end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false