summaryrefslogtreecommitdiffstats
path: root/lib/puppet/util.rb
Commit message (Collapse)AuthorAgeFilesLines
* Merge branch '2.6.x' into 2.7.xJacob Helwig2011-08-171-40/+16
|\ | | | | | | | | | | | | | | | | | | | | | | | | | | * 2.6.x: Reset indirector state after configurer tests. (#8770) Don't fail to set supplementary groups when changing user to root (#8770) Always fully drop privileges when changing user (#8662) Migrate suidmanager test case to rspec (#8740) Do not enumerate files in the root directory. (#3553) Explain that cron resources require time attributes Conflicts: lib/puppet/application/resource.rb test/puppet/tc_suidmanager.rb
| * (#8770) Always fully drop privileges when changing userNick Lewis2011-08-111-40/+16
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | On Mac OS X, it is only possible to directly change the euid of a process, and not the uid. Thus, when a puppet master started as root on OS X would change to the service user (puppet), it would leave the uid of its process set to 0. This allowed any type of Ruby plugin executed on the master (a type, provider, function, etc.) to trivially regain root privileges (by setting the euid of its process back to 0) and potentially compromise the master. Now, when permanently changing user, we will first try Process::UID.change_privilege, before falling back to setting the euid/uid ourselves. change_privilege correctly sets the uid of the process to the desired new uid, preventing the process from later escalating itself back to root. Similar behavior is also used when changing group. This has no effect on the behavior when temporarily changing user/group (for instance, to execute a single command or create a file as a particular user). Reviewed-By: Jacob Helwig <jacob@puppetlabs.com>
* | Merge branch '2.6.x' into 2.7.xMatt Robinson2011-07-141-1/+0
|\| | | | | | | | | | | | | | | | | | | | | * 2.6.x: (maint) Cleanup and strengthen acceptance tests (#7144) Update Settings#writesub to convert mode to Fixnum (maint) Fix platform dection for RHEL Manually Resolved Conflicts: acceptance/tests/ticket_5477_master_not_dectect_sitepp.rb spec/unit/util/settings_spec.rb
| * (#7144) Update Settings#writesub to convert mode to FixnumMax Martin2011-07-141-1/+0
| | | | | | | | | | | | | | | | Settings#writesub was not checking the type of the mode value passed in from the defaults, causing it to pass a string for mode to File.open, leading to failures. This commit resolves that issue. Paired-with: Matt Robinson <matt@puppetlabs.com>
* | (#7298) require 'English' to provide $CHILD_STATUS in Ruby 1.9Nick Lewis2011-05-161-0/+1
|/ | | | | | | | | This had been coming from 'cgi', but in Ruby 1.9, cgi no longer requires English. Since we use $CHILD_STATUS when execing, we need to have it available, so require it manually. This also provides the other named special globals, should we choose to use them. Paired-With: Josh Cooper
* Maint: Added the ability to replace the behavior ofPaul Berry2011-03-071-0/+5
| | | | | | | Puppet::Util.execute with an arbitrary code block for ease in spec testing. Reviewed-by: Max Martin <max@puppetlabs.com>
* Fix for #4299 -- Don't require whichMarkus Roberts2010-11-121-9/+4
| | | | | | We already had an internal implementation of which hiding under an assumed name (Puppet::Util.binary); this commit calls it out of hiding and uses it consisantly.
* Fix for #4955 -- Race condition & memory leak in Puppet::UtilMarkus Roberts2010-11-121-9/+16
| | | | | | | | | | | | | | The Puppet::Util.sync method was not thread safe and also leaked memory. I'm not certain, but I believe the first is ironic and the second is merely a bug. This patch addresses the problem by 1) refactoring so the sync objects are never returned (and thus no one can cache a reference to one) 2) adding reference counting 3) deleting them when they are no longer needed 4) doing the thread safty dance. It wasn't the first (or even second) solution considered, but it's the one that I was able to make work in a way that I'm convinced is correct. Its main advantage is that it puts all the tricky bits in one place.
* (#4763) Don't call a method that was removed in Rails 3 activerecordMatt Robinson2010-09-221-0/+8
| | | | | | | | | | Calling this method caused storeconfigs not to run. ActiveRecord::Base.allow_concurrency was deprecated in Rails 2.2. We support activerecord 2.1 and higher, so we still need to call this method for 2.1. I factored out the code that determines our activerecord version to a method in util so that the code was easier to read and test.
* Code smell: Two space indentationMarkus Roberts2010-07-091-381/+381
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Replaced 106806 occurances of ^( +)(.*$) with The ruby community almost universally (i.e. everyone but Luke, Markus, and the other eleven people who learned ruby in the 1900s) uses two-space indentation. 3 Examples: The code: end # Tell getopt which arguments are valid def test_get_getopt_args element = Setting.new :name => "foo", :desc => "anything", :settings => Puppet::Util::Settings.new assert_equal([["--foo", GetoptLong::REQUIRED_ARGUMENT]], element.getopt_args, "Did not produce appropriate getopt args") becomes: end # Tell getopt which arguments are valid def test_get_getopt_args element = Setting.new :name => "foo", :desc => "anything", :settings => Puppet::Util::Settings.new assert_equal([["--foo", GetoptLong::REQUIRED_ARGUMENT]], element.getopt_args, "Did not produce appropriate getopt args") The code: assert_equal(str, val) assert_instance_of(Float, result) end # Now test it with a passed object becomes: assert_equal(str, val) assert_instance_of(Float, result) end # Now test it with a passed object The code: end assert_nothing_raised do klass[:Yay] = "boo" klass["Cool"] = :yayness end becomes: end assert_nothing_raised do klass[:Yay] = "boo" klass["Cool"] = :yayness end
* Code smell: Avoid needless decorationsMarkus Roberts2010-07-091-3/+3
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * Replaced 704 occurances of (.*)\b([a-z_]+)\(\) with \1\2 3 Examples: The code: ctx = OpenSSL::SSL::SSLContext.new() becomes: ctx = OpenSSL::SSL::SSLContext.new The code: skip() becomes: skip The code: path = tempfile() becomes: path = tempfile * Replaced 31 occurances of ^( *)end *#.* with \1end 3 Examples: The code: becomes: The code: end # Dir.foreach becomes: end The code: end # def becomes: end
* Code smell: Avoid unneeded blocksMarkus Roberts2010-07-091-3/+1
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Replaced 45 occurances of (DEF) begin (LINES) rescue(.*) (LINES) end end with 3 Examples: The code: def find(name) begin self.const_get(name.to_s.capitalize) rescue puts "Unable to find application '#{name.to_s}'." Kernel::exit(1) end end becomes: def find(name) self.const_get(name.to_s.capitalize) rescue puts "Unable to find application '#{name.to_s}'." Kernel::exit(1) end The code: def exit_on_fail(message, code = 1) begin yield rescue RuntimeError, NotImplementedError => detail puts detail.backtrace if Puppet[:trace] $stderr.puts "Could not #{message}: #{detail}" exit(code) end end becomes: def exit_on_fail(message, code = 1) yield rescue RuntimeError, NotImplementedError => detail puts detail.backtrace if Puppet[:trace] $stderr.puts "Could not #{message}: #{detail}" exit(code) end The code: def start begin case ssl when :tls @connection = LDAP::SSLConn.new(host, port, true) when true @connection = LDAP::SSLConn.new(host, port) else @connection = LDAP::Conn.new(host, port) end @connection.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3) @connection.set_option(LDAP::LDAP_OPT_REFERRALS, LDAP::LDAP_OPT_ON) @connection.simple_bind(user, password) rescue => detail raise Puppet::Error, "Could not connect to LDAP: #{detail}" end end becomes: def start case ssl when :tls @connection = LDAP::SSLConn.new(host, port, true) when true @connection = LDAP::SSLConn.new(host, port) else @connection = LDAP::Conn.new(host, port) end @connection.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3) @connection.set_option(LDAP::LDAP_OPT_REFERRALS, LDAP::LDAP_OPT_ON) @connection.simple_bind(user, password) rescue => detail raise Puppet::Error, "Could not connect to LDAP: #{detail}" end
* Code smell: Avoid explicit returnsMarkus Roberts2010-07-091-6/+6
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Replaced 583 occurances of (DEF) (LINES) return (.*) end with 3 Examples: The code: def consolidate_failures(failed) filters = Hash.new { |h,k| h[k] = [] } failed.each do |spec, failed_trace| if f = test_files_for(failed).find { |f| failed_trace =~ Regexp.new(f) } filters[f] << spec break end end return filters end becomes: def consolidate_failures(failed) filters = Hash.new { |h,k| h[k] = [] } failed.each do |spec, failed_trace| if f = test_files_for(failed).find { |f| failed_trace =~ Regexp.new(f) } filters[f] << spec break end end filters end The code: def retrieve return_value = super return_value = return_value[0] if return_value && return_value.is_a?(Array) return return_value end becomes: def retrieve return_value = super return_value = return_value[0] if return_value && return_value.is_a?(Array) return_value end The code: def fake_fstab os = Facter['operatingsystem'] if os == "Solaris" name = "solaris.fstab" elsif os == "FreeBSD" name = "freebsd.fstab" else # Catchall for other fstabs name = "linux.fstab" end oldpath = @provider_class.default_target return fakefile(File::join("data/types/mount", name)) end becomes: def fake_fstab os = Facter['operatingsystem'] if os == "Solaris" name = "solaris.fstab" elsif os == "FreeBSD" name = "freebsd.fstab" else # Catchall for other fstabs name = "linux.fstab" end oldpath = @provider_class.default_target fakefile(File::join("data/types/mount", name)) end
* Code smell: Line modifiers are preferred to one-line blocks.Markus Roberts2010-07-091-21/+7
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * Replaced 6 occurances of (while .*?) *do$ with The do is unneeded in the block header form and causes problems with the block-to-one-line transformation. 3 Examples: The code: while line = f.gets do becomes: while line = f.gets The code: while line = shadow.gets do becomes: while line = shadow.gets The code: while wrapper = zeros.pop do becomes: while wrapper = zeros.pop * Replaced 19 occurances of ((if|unless) .*?) *then$ with The then is unneeded in the block header form and causes problems with the block-to-one-line transformation. 3 Examples: The code: if f = test_files_for(failed).find { |f| failed_trace =~ Regexp.new(f) } then becomes: if f = test_files_for(failed).find { |f| failed_trace =~ Regexp.new(f) } The code: unless defined?(@spec_command) then becomes: unless defined?(@spec_command) The code: if c == ?\n then becomes: if c == ?\n * Replaced 758 occurances of ((?:if|unless|while|until) .*) (.*) end with The one-line form is preferable provided: * The condition is not used to assign a variable * The body line is not already modified * The resulting line is not too long 3 Examples: The code: if Puppet.features.libshadow? has_feature :manages_passwords end becomes: has_feature :manages_passwords if Puppet.features.libshadow? The code: unless (defined?(@current_pool) and @current_pool) @current_pool = process_zpool_data(get_pool_data) end becomes: @current_pool = process_zpool_data(get_pool_data) unless (defined?(@current_pool) and @current_pool) The code: if Puppet[:trace] puts detail.backtrace end becomes: puts detail.backtrace if Puppet[:trace]
* Code smell: Use string interpolationMarkus Roberts2010-07-091-13/+13
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * Replaced 83 occurances of (.*)" *[+] *([$@]?[\w_0-9.:]+?)(.to_s\b)?(?! *[*(%\w_0-9.:{\[]) with \1#{\2}" 3 Examples: The code: puts "PUPPET " + status + ": " + process + ", " + state becomes: puts "PUPPET " + status + ": " + process + ", #{state}" The code: puts "PUPPET " + status + ": #{process}" + ", #{state}" becomes: puts "PUPPET #{status}" + ": #{process}" + ", #{state}" The code: }.compact.join( "\n" ) + "\n" + t + "]\n" becomes: }.compact.join( "\n" ) + "\n#{t}" + "]\n" * Replaced 21 occurances of (.*)" *[+] *" with \1 3 Examples: The code: puts "PUPPET #{status}" + ": #{process}" + ", #{state}" becomes: puts "PUPPET #{status}" + ": #{process}, #{state}" The code: puts "PUPPET #{status}" + ": #{process}, #{state}" becomes: puts "PUPPET #{status}: #{process}, #{state}" The code: res = self.class.name + ": #{@name}" + "\n" becomes: res = self.class.name + ": #{@name}\n" * Don't use string concatenation to split lines unless they would be very long. Replaced 11 occurances of (.*)(['"]) *[+] *(['"])(.*) with 3 Examples: The code: o.define_head "The check_puppet Nagios plug-in checks that specified " + "Puppet process is running and the state file is no " + becomes: o.define_head "The check_puppet Nagios plug-in checks that specified Puppet process is running and the state file is no " + The code: o.separator "Mandatory arguments to long options are mandatory for " + "short options too." becomes: o.separator "Mandatory arguments to long options are mandatory for short options too." The code: 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." becomes: 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." * Replaced no occurances of do (.*?) end with {\1} * Replaced 1488 occurances of "([^"\n]*%s[^"\n]*)" *% *(.+?)(?=$| *\b(do|if|while|until|unless|#)\b) with 20 Examples: The code: args[0].split(/\./).map do |s| "dc=%s"%[s] end.join(",") becomes: args[0].split(/\./).map do |s| "dc=#{s}" end.join(",") The code: puts "%s" % Puppet.version becomes: puts "#{Puppet.version}" The code: raise "Could not find information for %s" % node becomes: raise "Could not find information for #{node}" The code: raise Puppet::Error, "Cannot create %s: basedir %s is a file" % [dir, File.join(path)] becomes: raise Puppet::Error, "Cannot create #{dir}: basedir #{File.join(path)} is a file" The code: Puppet.err "Could not run %s: %s" % [client_class, detail] becomes: Puppet.err "Could not run #{client_class}: #{detail}" The code: raise "Could not find handler for %s" % arg becomes: raise "Could not find handler for #{arg}" The code: Puppet.err "Will not start without authorization file %s" % Puppet[:authconfig] becomes: Puppet.err "Will not start without authorization file #{Puppet[:authconfig]}" The code: raise Puppet::Error, "Could not deserialize catalog from pson: %s" % detail becomes: raise Puppet::Error, "Could not deserialize catalog from pson: #{detail}" The code: raise "Could not find facts for %s" % Puppet[:certname] becomes: raise "Could not find facts for #{Puppet[:certname]}" The code: raise ArgumentError, "%s is not readable" % path becomes: raise ArgumentError, "#{path} is not readable" The code: raise ArgumentError, "Invalid handler %s" % name becomes: raise ArgumentError, "Invalid handler #{name}" The code: debug "Executing '%s' in zone %s with '%s'" % [command, @resource[:name], str] becomes: debug "Executing '#{command}' in zone #{@resource[:name]} with '#{str}'" The code: raise Puppet::Error, "unknown cert type '%s'" % hash[:type] becomes: raise Puppet::Error, "unknown cert type '#{hash[:type]}'" The code: Puppet.info "Creating a new certificate request for %s" % Puppet[:certname] becomes: Puppet.info "Creating a new certificate request for #{Puppet[:certname]}" The code: "Cannot create alias %s: object already exists" % [name] becomes: "Cannot create alias #{name}: object already exists" The code: return "replacing from source %s with contents %s" % [metadata.source, metadata.checksum] becomes: return "replacing from source #{metadata.source} with contents #{metadata.checksum}" The code: it "should have a %s parameter" % param do becomes: it "should have a #{param} parameter" do The code: describe "when registring '%s' messages" % log do becomes: describe "when registring '#{log}' messages" do The code: paths = %w{a b c d e f g h}.collect { |l| "/tmp/iteration%stest" % l } becomes: paths = %w{a b c d e f g h}.collect { |l| "/tmp/iteration#{l}test" } The code: assert_raise(Puppet::Error, "Check '%s' did not fail on false" % check) do becomes: assert_raise(Puppet::Error, "Check '#{check}' did not fail on false") do
* Code smell: English names for special globals rather than line-noiseMarkus Roberts2010-07-091-2/+2
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * Replaced 36 occurances of [$][?] with $CHILD_STATUS 3 Examples: The code: print "%s finished with exit code %s\n" % [host, $?.exitstatus] becomes: print "%s finished with exit code %s\n" % [host, $CHILD_STATUS.exitstatus] The code: $stderr.puts "Could not find host for PID %s with status %s" % [pid, $?.exitstatus] becomes: $stderr.puts "Could not find host for PID %s with status %s" % [pid, $CHILD_STATUS.exitstatus] The code: unless $? == 0 becomes: unless $CHILD_STATUS == 0 * Replaced 3 occurances of [$][$] with $PID 3 Examples: The code: Process.kill(:HUP, $$) if restart_requested? becomes: Process.kill(:HUP, $PID) if restart_requested? The code: if pid == $$ becomes: if pid == $PID The code: host[:name] = "!invalid.hostname.$$$" becomes: host[:name] = "!invalid.hostname.$PID$" * Replaced 7 occurances of [$]& with $MATCH 3 Examples: The code: work.slice!(0, $&.length) becomes: work.slice!(0, $MATCH.length) The code: if $& becomes: if $MATCH The code: if $& becomes: if $MATCH * Replaced 28 occurances of [$]:(?!:) with $LOAD_PATH 3 Examples: The code: sitelibdir = $:.find { |x| x =~ /site_ruby/ } becomes: sitelibdir = $LOAD_PATH.find { |x| x =~ /site_ruby/ } The code: $:.unshift "lib" becomes: $LOAD_PATH.unshift "lib" The code: $:.shift becomes: $LOAD_PATH.shift * Replaced 3 occurances of [$]! with $ERROR_INFO 3 Examples: The code: $LOG.fatal("Problem reading #{filepath}: #{$!}") becomes: $LOG.fatal("Problem reading #{filepath}: #{$ERROR_INFO}") The code: $stderr.puts "Couldn't build man pages: " + $! becomes: $stderr.puts "Couldn't build man pages: " + $ERROR_INFO The code: $stderr.puts $!.message becomes: $stderr.puts $ERROR_INFO.message * Replaced 3 occurances of ^(.*)[$]" with \1$LOADED_FEATURES 3 Examples: The code: unless $".index 'racc/parser.rb' becomes: unless $LOADED_FEATURES.index 'racc/parser.rb' The code: $".push 'racc/parser.rb' becomes: $LOADED_FEATURES.push 'racc/parser.rb' The code: $".should be_include("tmp/myfile.rb") becomes: $LOADED_FEATURES.should be_include("tmp/myfile.rb")
* Code smell: Inconsistent indentation and related formatting issuesMarkus Roberts2010-07-091-11/+14
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * Replaced 163 occurances of defined\? +([@a-zA-Z_.0-9?=]+) with defined?(\1) This makes detecting subsequent patterns easier. 3 Examples: The code: if ! defined? @parse_config becomes: if ! defined?(@parse_config) The code: return @option_parser if defined? @option_parser becomes: return @option_parser if defined?(@option_parser) The code: if defined? @local and @local becomes: if defined?(@local) and @local * Eliminate trailing spaces. Replaced 428 occurances of ^(.*?) +$ with \1 1 file was skipped. test/ral/providers/host/parsed.rb because 0 * Replace leading tabs with an appropriate number of spaces. Replaced 306 occurances of ^(\t+)(.*) with Tabs are not consistently expanded in all environments. * Don't arbitrarily wrap on sprintf (%) operator. Replaced 143 occurances of (.*['"] *%) +(.*) with Splitting the line does nothing to aid clarity and hinders further refactorings. 3 Examples: The code: raise Puppet::Error, "Cannot create %s: basedir %s is a file" % [dir, File.join(path)] becomes: raise Puppet::Error, "Cannot create %s: basedir %s is a file" % [dir, File.join(path)] The code: Puppet.err "Will not start without authorization file %s" % Puppet[:authconfig] becomes: Puppet.err "Will not start without authorization file %s" % Puppet[:authconfig] The code: $stderr.puts "Could not find host for PID %s with status %s" % [pid, $?.exitstatus] becomes: $stderr.puts "Could not find host for PID %s with status %s" % [pid, $?.exitstatus] * Don't break short arrays/parameter list in two. Replaced 228 occurances of (.*) +(.*) with 3 Examples: The code: puts @format.wrap(type.provider(prov).doc, :indent => 4, :scrub => true) becomes: puts @format.wrap(type.provider(prov).doc, :indent => 4, :scrub => true) The code: assert(FileTest.exists?(daily), "Did not make daily graph for %s" % type) becomes: assert(FileTest.exists?(daily), "Did not make daily graph for %s" % type) The code: assert(prov.target_object(:first).read !~ /^notdisk/, "Did not remove thing from disk") becomes: assert(prov.target_object(:first).read !~ /^notdisk/, "Did not remove thing from disk") * If arguments must wrap, treat them all equally Replaced 510 occurances of lines ending in things like ...(foo, or ...(bar(1,3), with \1 \2 3 Examples: The code: midscope.to_hash(false), becomes: assert_equal( The code: botscope.to_hash(true), becomes: # bottomscope, then checking that we see the right stuff. The code: :path => link, becomes: * Replaced 4516 occurances of ^( *)(.*) with The present code base is supposed to use four-space indentation. In some places we failed to maintain that standard. These should be fixed regardless of the 2 vs. 4 space question. 15 Examples: The code: def run_comp(cmd) puts cmd results = [] old_sync = $stdout.sync $stdout.sync = true line = [] begin open("| #{cmd}", "r") do |f| until f.eof? do c = f.getc becomes: def run_comp(cmd) puts cmd results = [] old_sync = $stdout.sync $stdout.sync = true line = [] begin open("| #{cmd}", "r") do |f| until f.eof? do c = f.getc The code: s.gsub!(/.{4}/n, '\\\\u\&') } string.force_encoding(Encoding::UTF_8) string rescue Iconv::Failure => e raise GeneratorError, "Caught #{e.class}: #{e}" end else def utf8_to_pson(string) # :nodoc: string = string.gsub(/["\\\x0-\x1f]/) { MAP[$&] } string.gsub!(/( becomes: s.gsub!(/.{4}/n, '\\\\u\&') } string.force_encoding(Encoding::UTF_8) string rescue Iconv::Failure => e raise GeneratorError, "Caught #{e.class}: #{e}" end else def utf8_to_pson(string) # :nodoc: string = string.gsub(/["\\\x0-\x1f]/) { MAP[$&] } string.gsub!(/( The code: end } rvalues: rvalue | rvalues comma rvalue { if val[0].instance_of?(AST::ASTArray) result = val[0].push(val[2]) else result = ast AST::ASTArray, :children => [val[0],val[2]] end } becomes: end } rvalues: rvalue | rvalues comma rvalue { if val[0].instance_of?(AST::ASTArray) result = val[0].push(val[2]) else result = ast AST::ASTArray, :children => [val[0],val[2]] end } The code: #passwdproc = proc { @password } keytext = @key.export( OpenSSL::Cipher::DES.new(:EDE3, :CBC), @password ) File.open(@keyfile, "w", 0400) { |f| f << keytext } becomes: # passwdproc = proc { @password } keytext = @key.export( OpenSSL::Cipher::DES.new(:EDE3, :CBC), @password ) File.open(@keyfile, "w", 0400) { |f| f << keytext } The code: end def to_manifest "%s { '%s':\n%s\n}" % [self.type.to_s, self.name, @params.collect { |p, v| if v.is_a? Array " #{p} => [\'#{v.join("','")}\']" else " #{p} => \'#{v}\'" end }.join(",\n") becomes: end def to_manifest "%s { '%s':\n%s\n}" % [self.type.to_s, self.name, @params.collect { |p, v| if v.is_a? Array " #{p} => [\'#{v.join("','")}\']" else " #{p} => \'#{v}\'" end }.join(",\n") The code: via the augeas tool. Requires: - augeas to be installed (http://www.augeas.net) - ruby-augeas bindings Sample usage with a string:: augeas{\"test1\" : context => \"/files/etc/sysconfig/firstboot\", changes => \"set RUN_FIRSTBOOT YES\", becomes: via the augeas tool. Requires: - augeas to be installed (http://www.augeas.net) - ruby-augeas bindings Sample usage with a string:: augeas{\"test1\" : context => \"/files/etc/sysconfig/firstboot\", changes => \"set RUN_FIRSTBOOT YES\", The code: names.should_not be_include("root") end describe "when generating a purgeable resource" do it "should be included in the generated resources" do Puppet::Type.type(:host).stubs(:instances).returns [@purgeable_resource] @resources.generate.collect { |r| r.ref }.should include(@purgeable_resource.ref) end end describe "when the instance's do not have an ensure property" do becomes: names.should_not be_include("root") end describe "when generating a purgeable resource" do it "should be included in the generated resources" do Puppet::Type.type(:host).stubs(:instances).returns [@purgeable_resource] @resources.generate.collect { |r| r.ref }.should include(@purgeable_resource.ref) end end describe "when the instance's do not have an ensure property" do The code: describe "when the instance's do not have an ensure property" do it "should not be included in the generated resources" do @no_ensure_resource = Puppet::Type.type(:exec).new(:name => '/usr/bin/env echo') Puppet::Type.type(:host).stubs(:instances).returns [@no_ensure_resource] @resources.generate.collect { |r| r.ref }.should_not include(@no_ensure_resource.ref) end end describe "when the instance's ensure property does not accept absent" do it "should not be included in the generated resources" do @no_absent_resource = Puppet::Type.type(:service).new(:name => 'foobar') becomes: describe "when the instance's do not have an ensure property" do it "should not be included in the generated resources" do @no_ensure_resource = Puppet::Type.type(:exec).new(:name => '/usr/bin/env echo') Puppet::Type.type(:host).stubs(:instances).returns [@no_ensure_resource] @resources.generate.collect { |r| r.ref }.should_not include(@no_ensure_resource.ref) end end describe "when the instance's ensure property does not accept absent" do it "should not be included in the generated resources" do @no_absent_resource = Puppet::Type.type(:service).new(:name => 'foobar') The code: func = nil assert_nothing_raised do func = Puppet::Parser::AST::Function.new( :name => "template", :ftype => :rvalue, :arguments => AST::ASTArray.new( :children => [stringobj(template)] ) becomes: func = nil assert_nothing_raised do func = Puppet::Parser::AST::Function.new( :name => "template", :ftype => :rvalue, :arguments => AST::ASTArray.new( :children => [stringobj(template)] ) The code: assert( @store.allowed?("hostname.madstop.com", "192.168.1.50"), "hostname not allowed") assert( ! @store.allowed?("name.sub.madstop.com", "192.168.0.50"), "subname name allowed") becomes: assert( @store.allowed?("hostname.madstop.com", "192.168.1.50"), "hostname not allowed") assert( ! @store.allowed?("name.sub.madstop.com", "192.168.0.50"), "subname name allowed") The code: assert_nothing_raised { server = Puppet::Network::Handler.fileserver.new( :Local => true, :Config => false ) } becomes: assert_nothing_raised { server = Puppet::Network::Handler.fileserver.new( :Local => true, :Config => false ) } The code: 'yay', { :failonfail => false, :uid => @user.uid, :gid => @user.gid } ).returns('output') output = Puppet::Util::SUIDManager.run_and_capture 'yay', @user.uid, @user.gid becomes: 'yay', { :failonfail => false, :uid => @user.uid, :gid => @user.gid } ).returns('output') output = Puppet::Util::SUIDManager.run_and_capture 'yay', @user.uid, @user.gid The code: ).times(1) pkg.provider.expects( :aptget ).with( '-y', '-q', 'remove', 'faff' becomes: ).times(1) pkg.provider.expects( :aptget ).with( '-y', '-q', 'remove', 'faff' The code: johnny one two billy three four\n" # Just parse and generate, to make sure it's isomorphic. assert_nothing_raised do assert_equal(text, @parser.to_file(@parser.parse(text)), "parsing was not isomorphic") end end def test_valid_attrs becomes: johnny one two billy three four\n" # Just parse and generate, to make sure it's isomorphic. assert_nothing_raised do assert_equal(text, @parser.to_file(@parser.parse(text)), "parsing was not isomorphic") end end def test_valid_attrs The code: "testing", :onboolean => [true, "An on bool"], :string => ["a string", "A string arg"] ) result = [] should = [] assert_nothing_raised("Add args failed") do @config.addargs(result) end @config.each do |name, element| becomes: "testing", :onboolean => [true, "An on bool"], :string => ["a string", "A string arg"] ) result = [] should = [] assert_nothing_raised("Add args failed") do @config.addargs(result) end @config.each do |name, element|
* Code smell: Win32 --> MS_windowsMarkus Roberts2010-07-091-1/+1
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * Replaced 12 occurances of Win32 with Microsoft Windows 3 Examples: The code: # and all .rb files in lib/. This is disabled by default on Win32. becomes: # and all .rb files in lib/. This is disabled by default on Microsoft Windows. The code: # We can use Win32 functions becomes: # We can use Microsoft Windows functions The code: desc "Uses Win32 functionality to manage file's users and rights." becomes: desc "Uses Microsoft Windows functionality to manage file's users and rights." * Replaced 10 occurances of :win32 with :microsoft_windows 3 Examples: The code: Puppet.features.add(:win32, :libs => ["sys/admin", "win32/process", "win32/dir"]) becomes: Puppet.features.add(:microsoft_windows, :libs => ["sys/admin", "win32/process", "win32/dir"]) The code: Puppet::Type.type(:file).provide :win32 do becomes: Puppet::Type.type(:file).provide :microsoft_windows do The code: confine :feature => :win32 becomes: confine :feature => :microsoft_windows * Replaced 13 occurances of win32\? with microsoft_windows? 3 Examples: The code: signals.update({:HUP => :restart, :USR1 => :reload, :USR2 => :reopen_logs }) unless Puppet.features.win32? becomes: signals.update({:HUP => :restart, :USR1 => :reload, :USR2 => :reopen_logs }) unless Puppet.features.microsoft_windows? The code: raise Puppet::Error,"Cannot determine basic system flavour" unless Puppet.features.posix? or Puppet.features.win32? becomes: raise Puppet::Error,"Cannot determine basic system flavour" unless Puppet.features.posix? or Puppet.features.microsoft_windows? The code: require 'sys/admin' if Puppet.features.win32? becomes: require 'sys/admin' if Puppet.features.microsoft_windows?
* Implement "forking" for WindowsDavid Schmitt2010-02-171-24/+46
|
* Feature #2935: lazify require graph for applicationsJesse Wolfe2010-02-171-0/+1
| | | | | | | | | Because environments have to declare their mode before puppet tries to load defaults.rb, it reduces the complexity considerably to have application classes to load their lib dependencies at the last possible moment. Signed-off-by: Jesse Wolfe <jes5199@gmail.com>
* Fix for #3107 Changing users on AIXMarkus Roberts2010-02-171-18/+4
| | | | | | | | | | | | | | There are several issues with changing the real, effective, and saved group and user ids in different environments (which methods to call, in what order, etc). While the code being replaced by this patch appeared to work for Linux, Solaris, and (with a special case test) Darwin; it was failing under AIX and may have had edge-case problems under the others. Ruby back to 1.8.1 has supported a higher level interface that deals with the problem and captures a broader range of OSes; it's a single call for group and one for user--the details of rid/eid/svid, etc ordering are handled internally. Switching to that simplifies our code and should improve/unify our support of various OSes.
* Reversion of pipe IO patch for testing on #3025Markus Roberts2010-01-121-39/+54
|
* Fix for temporary file security wholeMarkus Roberts2010-01-051-0/+22
| | | | | | | | | | | | | | | | | | | | | | | We create temporary files in /tmp/ with predictable names. These could be used by an attacker to DoS a box by setting a symlink to some other file (say, /etc/shadow) and waiting for us to overwrite it. The minimalistic solution employed by this patch is to wrap all such file writing with a paranoid wrapper that: 1) Check to see if the target exists 2) Issues a warning if it was a symlink 3) Deletes it 4) Waits (0.1 seconds if it was a file, 5 seconds if it was a symlink) 5) Opens the file with EXCL, which will fail if the file has come back. If this succeeds (as it normally will) it has exactly the same semantics as the original code (a must, as we are right at a release boundary). However, under no circumstances will it follow a preexisting symlink (the operating system guarantees this with EXCL) so the danger of an exploit has been converted into the possibility of a failure, with an appropriate warning.
* Do not close stdout or stderr in execute.Ricky Zhou2010-01-021-9/+12
| | | | | | Closing stdout and stderr would sometimes cause failures when a program that is executed with squelched output tries to write to them. This reverts to the previous behavior of reopening them to /dev/null.
* Use a pipe instead of a temp file for command output.Ricky Zhou2010-01-011-54/+36
| | | | | | This solves some SELinux issues with programs such as mount being denied from writing to temporary files and removes a race condition with temporary file creation.
* Revert "Fix for #2731 (problem communicating with processes in SELinux)"James Turnbull2009-12-311-22/+51
| | | | | | Due to problems introduced on HP-UX (See #2997) This reverts commit 6ab2453d966d1d48e12d8a8cec34b9e460597d04.
* Fix for #2731 (problem communicating with processes in SELinux)Markus Roberts2009-12-231-51/+22
| | | | | | | | | | In some cases communicating with child processes via temprary files is not viable. This is Ricky Zhou's patch from the ticket, which solves the problem by using the more normal system of pipes. It is a broader reaching change than suggested by the ticket (it affects all execs, not just SELinux) but IMHO is the right way to go. Signed-off-by: Markus Roberts <Markus@reality.com>
* Fixed #1806 - supplementary groups are not resetJames Turnbull2009-11-201-2/+3
| | | | | | Patch thanks to Till Maas Signed-off-by: James Turnbull <james@lovedthanlost.net>
* Fixes #1719, this avoids calling the external binary *which* everytime we ↵Ohad Levy2009-10-131-11/+6
| | | | are looking for a binary
* Monkey patch to improve yaml compatibility between ruby versionsMarkus Roberts2009-09-051-0/+1
| | | | | | | | | Ruby 1.8.1 can not parse the yanl produced by later versions because it requires explict type tagging of symbols. This patch adds the tagging on to later versions so that mixed version instalations can use yaml. Signed-off-by: Markus Roberts <Markus@reality.com>
* Fixes #724 - false is equivalent to 'ruby -W1'Marc Fournier2009-09-011-1/+1
| | | | Signed-off-by: Marc Fournier <marc.fournier@camptocamp.com>
* Removing chuser on darwin restrictionLuke Kanies2009-08-241-4/+0
| | | | | | | | | | | For too long we have refused to change users on Darwin because a long time ago the ruby they shipped with was really, really broken. It's been fixed for a while, so this just removes the restriction. Signed-off-by: Luke Kanies <luke@madstop.com>
* Removed extra whitespace from end of linesIan Taylor2009-06-061-8/+8
|
* Changed tabs to spaces without interfering with indentation or alignmentIan Taylor2009-06-061-1/+1
|
* Preparing to fix #1812 - Moving locking code to a moduleLuke Kanies2008-12-121-34/+2
| | | | | | | This moves the locking code out of Puppet::Util into a separate module, to make the code cleaner. Signed-off-by: Luke Kanies <luke@madstop.com>
* add some more sanity checks around stdinNigel Kersten2008-12-061-3/+9
|
* add support for stdin to Puppet::Util.executeNigel Kersten2008-12-061-2/+2
|
* Fixed #1752 - Add an optional argument to Puppet::Util.execute to determine ↵James Turnbull2008-11-191-2/+7
| | | | whether stderr and stdout are combined in the output
* Fixing a test that was failing because i-have-no-ideaLuke Kanies2008-10-081-1/+5
| | | | Signed-off-by: Luke Kanies <luke@madstop.com>
* Fixed issues with file descriptors leaking into subprocessesJames Turnbull2008-09-131-0/+1
|
* Fixed #1571 - Puppet::Util::binary returns incorrect resultsJames Turnbull2008-09-131-8/+3
|
* Fixed #1414 - Return code from waitpid now right shifted 8 bitsJames Turnbull2008-07-171-1/+1
|
* Found all instances of methods where split() is used withoutLuke Kanies2008-03-211-1/+2
| | | | | | | | | | any local variables and added a local variable -- see http://snurl.com/21zf8. My own testing showed that this caused memory growth to level off at a reasonable level. Note that the link above says the problem is only with class methods, but my own testing showed that it's any method that meets these criteria. This is not a functional change, but should hopefully be the last nail in the coffin of #1131.
* Removing the Id tags from all of the filesLuke Kanies2007-10-031-1/+0
|
* The new configuration handler looks to be ready for usage. Now I just need ↵Luke Kanies2007-08-151-1/+1
| | | | to convert the interpreter to use SimpleNode objects, then continue with the Configuration object.
* Hopefully fixing #720 -- I added tests and a lame back-off system to give ↵luke2007-07-191-3/+24
| | | | | | the child process time to write git-svn-id: https://reductivelabs.com/svn/puppet/trunk@2717 980ebf18-57e1-0310-9a29-db15c13687c0
* Removing the chdir from util.rb, I forgot that the directory often mattersluke2007-07-191-1/+0
| | | | git-svn-id: https://reductivelabs.com/svn/puppet/trunk@2712 980ebf18-57e1-0310-9a29-db15c13687c0
* Hopefully fixing #640, and maybe some warnings at the same time. I added a ↵luke2007-07-191-0/+2
| | | | | | call to Process.setsid after the fork, and I chdir'd to /. git-svn-id: https://reductivelabs.com/svn/puppet/trunk@2711 980ebf18-57e1-0310-9a29-db15c13687c0
* Trying to get rid of the warning from #724luke2007-07-181-0/+3
| | | | git-svn-id: https://reductivelabs.com/svn/puppet/trunk@2703 980ebf18-57e1-0310-9a29-db15c13687c0
* Adding the output_file.close, as wyvern recommendedluke2007-06-181-0/+1
| | | | git-svn-id: https://reductivelabs.com/svn/puppet/trunk@2605 980ebf18-57e1-0310-9a29-db15c13687c0