diff options
author | Markus Roberts <Markus@reality.com> | 2010-07-09 18:12:17 -0700 |
---|---|---|
committer | Markus Roberts <Markus@reality.com> | 2010-07-09 18:12:17 -0700 |
commit | 3180b9d9b2c844dade1d361326600f7001ec66dd (patch) | |
tree | 98fe7c5ac7eb942aac9c39f019a17b0b3f5a57f4 /ext | |
parent | 543225970225de5697734bfaf0a6eee996802c04 (diff) | |
download | puppet-3180b9d9b2c844dade1d361326600f7001ec66dd.tar.gz puppet-3180b9d9b2c844dade1d361326600f7001ec66dd.tar.xz puppet-3180b9d9b2c844dade1d361326600f7001ec66dd.zip |
Code smell: Two space indentation
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
Diffstat (limited to 'ext')
-rw-r--r-- | ext/extlookup.rb | 170 | ||||
-rwxr-xr-x | ext/nagios/check_puppet.rb | 166 | ||||
-rwxr-xr-x | ext/puppetlisten/puppetlisten.rb | 76 | ||||
-rwxr-xr-x | ext/puppetlisten/puppetrun.rb | 8 | ||||
-rw-r--r-- | ext/puppetstoredconfigclean.rb | 90 | ||||
-rw-r--r-- | ext/pure_ruby_dsl/dsl_test.rb | 4 | ||||
-rw-r--r-- | ext/regexp_nodes/regexp_nodes.rb | 248 | ||||
-rwxr-xr-x | ext/yaml_nodes.rb | 68 |
8 files changed, 415 insertions, 415 deletions
diff --git a/ext/extlookup.rb b/ext/extlookup.rb index 24b161e0f..b72fc1287 100644 --- a/ext/extlookup.rb +++ b/ext/extlookup.rb @@ -80,102 +80,102 @@ require 'csv' module Puppet::Parser::Functions - newfunction(:extlookup, :type => :rvalue) do |args| - key = args[0] - default = "_ExtUNSET_" - datafile = "_ExtUNSET_" - - default = args[1] if args[1] - datafile = args[2] if args[2] - - extlookup_datadir = lookupvar('extlookup_datadir') - extlookup_precedence = Array.new - - # precedence values can have variables embedded in them - # in the form %{fqdn}, you could for example do - # - # $extlookup_precedence = ["hosts/%{fqdn}", "common"] - # - # this will result in /path/to/extdata/hosts/your.box.com.csv - # being searched. - # - # we parse the precedence here because the best place to specify - # it would be in site.pp but site.pp is only evaluated at startup - # so $fqdn etc would have no meaning there, this way it gets evaluated - # each run and has access to the right variables for that run - lookupvar('extlookup_precedence').each do |prec| - while prec =~ /%\{(.+?)\}/ - prec.gsub!(/%\{#{$1}\}/, lookupvar($1)) - end + newfunction(:extlookup, :type => :rvalue) do |args| + key = args[0] + default = "_ExtUNSET_" + datafile = "_ExtUNSET_" + + default = args[1] if args[1] + datafile = args[2] if args[2] + + extlookup_datadir = lookupvar('extlookup_datadir') + extlookup_precedence = Array.new + + # precedence values can have variables embedded in them + # in the form %{fqdn}, you could for example do + # + # $extlookup_precedence = ["hosts/%{fqdn}", "common"] + # + # this will result in /path/to/extdata/hosts/your.box.com.csv + # being searched. + # + # we parse the precedence here because the best place to specify + # it would be in site.pp but site.pp is only evaluated at startup + # so $fqdn etc would have no meaning there, this way it gets evaluated + # each run and has access to the right variables for that run + lookupvar('extlookup_precedence').each do |prec| + while prec =~ /%\{(.+?)\}/ + prec.gsub!(/%\{#{$1}\}/, lookupvar($1)) + end + + extlookup_precedence << prec + end - extlookup_precedence << prec - end + datafiles = Array.new - datafiles = Array.new + # if we got a custom data file, put it first in the array of search files + if datafile != "" + datafiles << extlookup_datadir + "/#{datafile}.csv" if File.exists?(extlookup_datadir + "/#{datafile}.csv") + end - # if we got a custom data file, put it first in the array of search files - if datafile != "" - datafiles << extlookup_datadir + "/#{datafile}.csv" if File.exists?(extlookup_datadir + "/#{datafile}.csv") - end + extlookup_precedence.each do |d| + datafiles << extlookup_datadir + "/#{d}.csv" + end - extlookup_precedence.each do |d| - datafiles << extlookup_datadir + "/#{d}.csv" - end + desired = "_ExtUNSET_" + + datafiles.each do |file| + parser.watch_file(file) if File.exists?(file) + + if desired == "_ExtUNSET_" + if File.exists?(file) + result = CSV.read(file).find_all do |r| + r[0] == key + end - desired = "_ExtUNSET_" - - datafiles.each do |file| - parser.watch_file(file) if File.exists?(file) - - if desired == "_ExtUNSET_" - if File.exists?(file) - result = CSV.read(file).find_all do |r| - r[0] == key - end - - - # return just the single result if theres just one, - # else take all the fields in the csv and build an array - if result.length > 0 - if result[0].length == 2 - val = result[0][1].to_s - - # parse %{}'s in the CSV into local variables using lookupvar() - while val =~ /%\{(.+?)\}/ - val.gsub!(/%\{#{$1}\}/, lookupvar($1)) - end - - desired = val - elsif result[0].length > 1 - length = result[0].length - cells = result[0][1,length] - - # Individual cells in a CSV result are a weird data type and throws - # puppets yaml parsing, so just map it all to plain old strings - desired = cells.map do |c| - # parse %{}'s in the CSV into local variables using lookupvar() - while c =~ /%\{(.+?)\}/ - c.gsub!(/%\{#{$1}\}/, lookupvar($1)) - end - - c.to_s - end - end - end + + # return just the single result if theres just one, + # else take all the fields in the csv and build an array + if result.length > 0 + if result[0].length == 2 + val = result[0][1].to_s + + # parse %{}'s in the CSV into local variables using lookupvar() + while val =~ /%\{(.+?)\}/ + val.gsub!(/%\{#{$1}\}/, lookupvar($1)) + end + + desired = val + elsif result[0].length > 1 + length = result[0].length + cells = result[0][1,length] + + # Individual cells in a CSV result are a weird data type and throws + # puppets yaml parsing, so just map it all to plain old strings + desired = cells.map do |c| + # parse %{}'s in the CSV into local variables using lookupvar() + while c =~ /%\{(.+?)\}/ + c.gsub!(/%\{#{$1}\}/, lookupvar($1)) end - end - end - # don't accidently return nil's and such rather throw a parse error - if desired == "_ExtUNSET_" && default == "_ExtUNSET_" - raise Puppet::ParseError, "No match found for '#{key}' in any data file during extlookup()" - else - desired = default if desired == "_ExtUNSET_" + c.to_s + end + end + end end + end + end - desired + # don't accidently return nil's and such rather throw a parse error + if desired == "_ExtUNSET_" && default == "_ExtUNSET_" + raise Puppet::ParseError, "No match found for '#{key}' in any data file during extlookup()" + else + desired = default if desired == "_ExtUNSET_" end + + desired + end end # vi:tabstop=4:expandtab:ai diff --git a/ext/nagios/check_puppet.rb b/ext/nagios/check_puppet.rb index 4873c033b..85807f122 100755 --- a/ext/nagios/check_puppet.rb +++ b/ext/nagios/check_puppet.rb @@ -6,114 +6,114 @@ include Sys class CheckPuppet - VERSION = '0.1' - script_name = File.basename($0) + VERSION = '0.1' + script_name = File.basename($0) - # default options - OPTIONS = { - :statefile => "/var/lib/puppet/state/state.yaml", - :process => "puppetd", - :interval => 30, - } + # default options + OPTIONS = { + :statefile => "/var/lib/puppet/state/state.yaml", + :process => "puppetd", + :interval => 30, + } - o = 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 = 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", + o.on( + "-s", "--statefile=statefile", String, "The state file", - "Default: #{OPTIONS[:statefile]}") { |OPTIONS[:statefile]| } + "Default: #{OPTIONS[:statefile]}") { |OPTIONS[:statefile]| } - o.on( - "-p", "--process=processname", String, "The process to check", + o.on( + "-p", "--process=processname", String, "The process to check", - "Default: #{OPTIONS[:process]}") { |OPTIONS[:process]| } + "Default: #{OPTIONS[:process]}") { |OPTIONS[:process]| } - o.on( - "-i", "--interval=value", Integer, + o.on( + "-i", "--interval=value", Integer, - "Default: #{OPTIONS[:interval]} minutes") { |OPTIONS[:interval]| } + "Default: #{OPTIONS[:interval]} minutes") { |OPTIONS[:interval]| } - o.separator "" - o.on_tail("-h", "--help", "Show this help message.") do - puts o - exit - end + o.separator "" + o.on_tail("-h", "--help", "Show this help message.") do + puts o + exit + end + + o.parse!(ARGV) + end - o.parse!(ARGV) + def check_proc + + unless ProcTable.ps.find { |p| p.name == OPTIONS[:process]} + @proc = 2 + else + @proc = 0 end - def check_proc + end + + def check_state - unless ProcTable.ps.find { |p| p.name == OPTIONS[:process]} - @proc = 2 - else - @proc = 0 - end + # Set variables + curt = Time.now + intv = OPTIONS[:interval] * 60 + # Check file time + begin + @modt = File.mtime("#{OPTIONS[:statefile]}") + rescue + @file = 3 end - def check_state + diff = (curt - @modt).to_i - # Set variables - curt = Time.now - intv = OPTIONS[:interval] * 60 + if diff > intv + @file = 2 + else + @file = 0 + end - # Check file time - begin - @modt = File.mtime("#{OPTIONS[:statefile]}") - rescue - @file = 3 - end + end - diff = (curt - @modt).to_i + def output_status - if diff > intv - @file = 2 - else - @file = 0 - end + 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 - 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 @proc or @file - when 0 - status = "OK" - exitcode = 0 - when 2 - status = "CRITICAL" - exitcode = 2 - when 3 - status = "UNKNOWN" - exitcide = 3 - end - - puts "PUPPET #{status}: #{process}, #{state}" - exit(exitcode) + case @proc or @file + when 0 + status = "OK" + exitcode = 0 + when 2 + status = "CRITICAL" + exitcode = 2 + when 3 + status = "UNKNOWN" + exitcide = 3 end + + puts "PUPPET #{status}: #{process}, #{state}" + exit(exitcode) + end end cp = CheckPuppet.new diff --git a/ext/puppetlisten/puppetlisten.rb b/ext/puppetlisten/puppetlisten.rb index fd187c81b..9c1709cde 100755 --- a/ext/puppetlisten/puppetlisten.rb +++ b/ext/puppetlisten/puppetlisten.rb @@ -25,24 +25,24 @@ ctx.ca_file = Puppet[:localcacert] allowed_servers = Array.new runner = false; File.open(Puppet[:authconfig]).each do |line| - case line - when /^\s*#/: next # skip comments - when /^\s*$/: next # skip blank lines - when /\[puppetrunner\]/: # puppetrunner section - runner=true - when /^\s*(\w+)\s+(.+)$/: - var = $1 - value = $2 - case var - when "allow": - value.split(/\s*,\s*/).each { |val| - allowed_servers << val - puts "allowing #{val} access" - } if runner==true - end - else - runner=false + case line + when /^\s*#/: next # skip comments + when /^\s*$/: next # skip blank lines + when /\[puppetrunner\]/: # puppetrunner section + runner=true + when /^\s*(\w+)\s+(.+)$/: + var = $1 + value = $2 + case var + when "allow": + value.split(/\s*,\s*/).each { |val| + allowed_servers << val + puts "allowing #{val} access" + } if runner==true end + else + runner=false + end end # be a daemon @@ -50,27 +50,27 @@ sock = TCPServer.new(port) ssls = OpenSSL::SSL::SSLServer.new(sock, ctx) loop do - begin - ns = ssls.accept # start SSL session - af, port, host, ip = ns.peeraddr - print "connection from #{host+"("+ip+")"} " - if allowed_servers.include?(host) - #TODO add support for tags and other command line arguments - puts "accepted" - ns.puts "Executing #{cmd} on #{Facter.fqdn}.\n*******OUTPUT********\n\n" - IO.popen(cmd) do |f| - while line = f.gets - ns.puts line - end - end - ns.puts "\n*********DONE**********" - else - ns.puts "denied\n" - puts "denied" + begin + ns = ssls.accept # start SSL session + af, port, host, ip = ns.peeraddr + print "connection from #{host+"("+ip+")"} " + if allowed_servers.include?(host) + #TODO add support for tags and other command line arguments + puts "accepted" + ns.puts "Executing #{cmd} on #{Facter.fqdn}.\n*******OUTPUT********\n\n" + IO.popen(cmd) do |f| + while line = f.gets + ns.puts line end - ns.close - rescue - ns.close - next + end + ns.puts "\n*********DONE**********" + else + ns.puts "denied\n" + puts "denied" end + ns.close + rescue + ns.close + next + end end diff --git a/ext/puppetlisten/puppetrun.rb b/ext/puppetlisten/puppetrun.rb index 7aa0919cb..2fe31b7f4 100755 --- a/ext/puppetlisten/puppetrun.rb +++ b/ext/puppetlisten/puppetrun.rb @@ -6,10 +6,10 @@ port = 8139 if ARGV[0].nil? - warn "Usage: hostname to run against" - exit 1 + warn "Usage: hostname to run against" + exit 1 else - host = ARGV[0] + host = ARGV[0] end require 'puppet/sslcertificates/support' @@ -33,7 +33,7 @@ ssl.connect # start SSL session ssl.sync_close = true # if true the underlying socket will be # closed in SSLSocket#close. (default: false) while (line = ssl.gets) - puts line + puts line end ssl.close diff --git a/ext/puppetstoredconfigclean.rb b/ext/puppetstoredconfigclean.rb index 4d7350ca4..34dd72f5d 100644 --- a/ext/puppetstoredconfigclean.rb +++ b/ext/puppetstoredconfigclean.rb @@ -11,42 +11,42 @@ require 'getoptlong' config = '/etc/puppet/puppet.conf' def printusage(error_code) - puts "Usage: #{$0} [ list of hostnames as stored in hosts table ]" - puts "\n Options:" - puts "--config <puppet config file>" - exit(error_code) + puts "Usage: #{$0} [ list of hostnames as stored in hosts table ]" + puts "\n Options:" + puts "--config <puppet config file>" + exit(error_code) end - opts = GetoptLong.new( + opts = GetoptLong.new( - [ "--config", "-c", GetoptLong::REQUIRED_ARGUMENT ], - [ "--help", "-h", GetoptLong::NO_ARGUMENT ], - [ "--usage", "-u", GetoptLong::NO_ARGUMENT ], + [ "--config", "-c", GetoptLong::REQUIRED_ARGUMENT ], + [ "--help", "-h", GetoptLong::NO_ARGUMENT ], + [ "--usage", "-u", GetoptLong::NO_ARGUMENT ], - [ "--version", "-v", GetoptLong::NO_ARGUMENT ] + [ "--version", "-v", GetoptLong::NO_ARGUMENT ] ) begin - opts.each do |opt, arg| - case opt - when "--config" - config = arg + opts.each do |opt, arg| + case opt + when "--config" + config = arg - when "--help" - printusage(0) + when "--help" + printusage(0) - when "--usage" - printusage(0) + when "--usage" + printusage(0) - when "--version" - puts "#{Puppet.version}" - exit - end + when "--version" + puts "#{Puppet.version}" + exit end + end rescue GetoptLong::InvalidOption => detail - $stderr.puts "Try '#{$0} --help'" - exit(1) + $stderr.puts "Try '#{$0} --help'" + exit(1) end printusage(1) unless ARGV.size > 0 @@ -60,20 +60,20 @@ adapter = pm_conf[:dbadapter] args = {:adapter => adapter, :log_level => pm_conf[:rails_loglevel]} case adapter - when "sqlite3" - args[:dbfile] = pm_conf[:dblocation] - when "mysql", "postgresql" - args[:host] = pm_conf[:dbserver] unless pm_conf[:dbserver].to_s.empty? - args[:username] = pm_conf[:dbuser] unless pm_conf[:dbuser].to_s.empty? - args[:password] = pm_conf[:dbpassword] unless pm_conf[:dbpassword].to_s.empty? - args[:database] = pm_conf[:dbname] unless pm_conf[:dbname].to_s.empty? - args[:port] = pm_conf[:dbport] unless pm_conf[:dbport].to_s.empty? - socket = pm_conf[:dbsocket] - args[:socket] = socket unless socket.to_s.empty? - connections = pm_conf[:dbconnections].to_i - args[:pool] = connections if connections > 0 - else - raise ArgumentError, "Invalid db adapter #{adapter}" + when "sqlite3" + args[:dbfile] = pm_conf[:dblocation] + when "mysql", "postgresql" + args[:host] = pm_conf[:dbserver] unless pm_conf[:dbserver].to_s.empty? + args[:username] = pm_conf[:dbuser] unless pm_conf[:dbuser].to_s.empty? + args[:password] = pm_conf[:dbpassword] unless pm_conf[:dbpassword].to_s.empty? + args[:database] = pm_conf[:dbname] unless pm_conf[:dbname].to_s.empty? + args[:port] = pm_conf[:dbport] unless pm_conf[:dbport].to_s.empty? + socket = pm_conf[:dbsocket] + args[:socket] = socket unless socket.to_s.empty? + connections = pm_conf[:dbconnections].to_i + args[:pool] = connections if connections > 0 + else + raise ArgumentError, "Invalid db adapter #{adapter}" end args[:database] = "puppet" unless not args[:database].to_s.empty? @@ -81,13 +81,13 @@ args[:database] = "puppet" unless not args[:database].to_s.empty? ActiveRecord::Base.establish_connection(args) ARGV.each { |hostname| - if @host = Puppet::Rails::Host.find_by_name(hostname.strip) - print "Killing #{hostname}..." - $stdout.flush - @host.destroy - puts "done." - else - puts "Can't find host #{hostname}." - end + if @host = Puppet::Rails::Host.find_by_name(hostname.strip) + print "Killing #{hostname}..." + $stdout.flush + @host.destroy + puts "done." + else + puts "Can't find host #{hostname}." + end } exit 0 diff --git a/ext/pure_ruby_dsl/dsl_test.rb b/ext/pure_ruby_dsl/dsl_test.rb index 6eff2982e..97bb7cc60 100644 --- a/ext/pure_ruby_dsl/dsl_test.rb +++ b/ext/pure_ruby_dsl/dsl_test.rb @@ -1,7 +1,7 @@ hostclass "foobar" do - notify "this is a test", "loglevel" => "warning" + notify "this is a test", "loglevel" => "warning" end node "default" do - acquire "foobar" + acquire "foobar" end diff --git a/ext/regexp_nodes/regexp_nodes.rb b/ext/regexp_nodes/regexp_nodes.rb index 7633e5cea..e234985ca 100644 --- a/ext/regexp_nodes/regexp_nodes.rb +++ b/ext/regexp_nodes/regexp_nodes.rb @@ -58,129 +58,129 @@ WORKINGDIR = Dir.pwd # and a special version of to_yaml class ExternalNode - # Make these instance variables get/set-able with eponymous methods - attr_accessor :classes, :parameters, :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/') - # instance variables that contain the lists of classes and parameters - @hostname - @classes = Set.new ["baseclass"] - @parameters = Hash.new("unknown") # sets a default value of "unknown" - - self.parse_argv(hostname) - self.match_classes(WORKINGDIR + "/#{classdir}") - self.match_parameters(WORKINGDIR + "/#{parameterdir}") + # Make these instance variables get/set-able with eponymous methods + attr_accessor :classes, :parameters, :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/') + # instance variables that contain the lists of classes and parameters + @hostname + @classes = Set.new ["baseclass"] + @parameters = Hash.new("unknown") # sets a default value of "unknown" + + self.parse_argv(hostname) + self.match_classes(WORKINGDIR + "/#{classdir}") + self.match_parameters(WORKINGDIR + "/#{parameterdir}") + 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 + else + $LOG.fatal("didn't receive parsable hostname, got: [#{hostname}]") + exit(1) 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 - else - $LOG.fatal("didn't receive parsable hostname, got: [#{hostname}]") - 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 - - # 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}).to_yaml + ({ 'classes' => classes, 'parameters' => parameters}).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 + open(filepath).each { |l| + pattern = %r{#{l.chomp!}} + patternlist << pattern + $LOG.debug("appending [#{pattern}] to patternlist for [#{filepath}]") + } + rescue Exception + $LOG.fatal("Problem reading #{filepath}: #{$ERROR_INFO}") + exit(1) 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 - open(filepath).each { |l| - pattern = %r{#{l.chomp!}} - patternlist << pattern - $LOG.debug("appending [#{pattern}] to patternlist for [#{filepath}]") - } - rescue Exception - $LOG.fatal("Problem reading #{filepath}: #{$ERROR_INFO}") - exit(1) - end - - $LOG.debug("list of patterns for #{filepath}: #{patternlist}") + $LOG.debug("list of patterns for #{filepath}: #{patternlist}") - if matchthis =~ Regexp.union(patternlist) - $LOG.debug("matched #{$~.to_s} in #{matchthis}, returning true") - return true - - else # hostname didn't match anything in patternlist - $LOG.debug("#{matchthis} unmatched, returning false") - return nil - end + if matchthis =~ Regexp.union(patternlist) + $LOG.debug("matched #{$~.to_s} in #{matchthis}, returning true") + return true + else # hostname didn't match anything in patternlist + $LOG.debug("#{matchthis} unmatched, returning false") + return nil end - # 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) - $LOG.debug("Attempting to match [#{@hostname}] in [#{filepath}]") - if matched_in_patternfile?(filepath,@hostname) - @classes << patternfile.to_s - $LOG.debug("Appended #{patternfile.to_s} to classes instance variable") - end - end + end + + # 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) + $LOG.debug("Attempting to match [#{@hostname}] in [#{filepath}]") + if matched_in_patternfile?(filepath,@hostname) + @classes << patternfile.to_s + $LOG.debug("Appended #{patternfile.to_s} to classes instance variable") + 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 /var/lib/puppet/bin/parameters/environment/production - # ^prodweb - # would set parameters["environment"] = "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.debug "Considering contents of #{filepath}" - - Dir.foreach("#{filepath}") do |patternfile| - secondlevel = "#{filepath}/#{patternfile}" - $LOG.debug "Found parameters patternfile at #{secondlevel}" - next unless File.file?(secondlevel) and - File.readable?(secondlevel) - $LOG.debug("Attempting to match [#{@hostname}] in [#{secondlevel}]") - if matched_in_patternfile?(secondlevel, @hostname) - @parameters[ parametername.to_s ] = patternfile.to_s - $LOG.debug("Set @parameters[#{parametername.to_s}] = #{patternfile.to_s}") - 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 /var/lib/puppet/bin/parameters/environment/production + # ^prodweb + # would set parameters["environment"] = "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.debug "Considering contents of #{filepath}" + + Dir.foreach("#{filepath}") do |patternfile| + secondlevel = "#{filepath}/#{patternfile}" + $LOG.debug "Found parameters patternfile at #{secondlevel}" + next unless File.file?(secondlevel) and + File.readable?(secondlevel) + $LOG.debug("Attempting to match [#{@hostname}] in [#{secondlevel}]") + if matched_in_patternfile?(secondlevel, @hostname) + @parameters[ parametername.to_s ] = patternfile.to_s + $LOG.debug("Set @parameters[#{parametername.to_s}] = #{patternfile.to_s}") end + end end + end end @@ -188,22 +188,22 @@ end # happen as we initialize a subclass class MyExternalNode < ExternalNode - def initialize(hostname, classdir = 'classes/', parameterdir = 'parameters/') + def initialize(hostname, classdir = 'classes/', parameterdir = 'parameters/') - super + 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 + # 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.debug("matched hostclass #{hostclass}") - @parameters[ "hostclass" ] = hostclass - else - $LOG.debug("hostclass couldn't figure out class from #{@hostname}") - end + hostclass = match[2] + $LOG.debug("matched hostclass #{hostclass}") + @parameters[ "hostclass" ] = hostclass + else + $LOG.debug("hostclass couldn't figure out class from #{@hostname}") end + end end diff --git a/ext/yaml_nodes.rb b/ext/yaml_nodes.rb index b6c191a73..2174da09d 100755 --- a/ext/yaml_nodes.rb +++ b/ext/yaml_nodes.rb @@ -39,27 +39,27 @@ BASEDIR = Dir.chdir(File.dirname(__FILE__) + "/..") { Dir.getwd } options = {:yamldir => File.join(BASEDIR, "yaml")} OptionParser.new do |opts| - opts.banner = "Usage: yaml-nodes [options] <host>" + opts.banner = "Usage: yaml-nodes [options] <host>" - opts.on("-y dir", "--yamldir dir", "Specify the directory with the YAML files") do |arg| - raise "YAML directory #{arg} does not exist or is not a directory" unless FileTest.directory?(arg) - options[:yamldir] = arg - end + opts.on("-y dir", "--yamldir dir", "Specify the directory with the YAML files") do |arg| + raise "YAML directory #{arg} does not exist or is not a directory" unless FileTest.directory?(arg) + options[:yamldir] = arg + end - opts.on("-h", "--help", "Print this help") do - puts opts.help - exit(0) - end + opts.on("-h", "--help", "Print this help") do + puts opts.help + exit(0) + end end.parse! # Read in a pure yaml representation of our node. def read_node(node) - nodefile = File.join(YAMLDIR, "#{node}.yaml") - if FileTest.exist?(nodefile) - return YAML.load_file(nodefile) - else - raise "Could not find information for #{node}" - end + nodefile = File.join(YAMLDIR, "#{node}.yaml") + if FileTest.exist?(nodefile) + return YAML.load_file(nodefile) + else + raise "Could not find information for #{node}" + end end node = ARGV[0] @@ -69,31 +69,31 @@ info = read_node(node) # Iterate over any provided parents, merging in there information. parents_seen = [] while parent = info["parent"] - raise "Found inheritance loop with parent #{parent}" if parents_seen.include?(parent) + raise "Found inheritance loop with parent #{parent}" if parents_seen.include?(parent) - parents_seen << parent + parents_seen << parent - info.delete("parent") + info.delete("parent") - parent_info = read_node(parent) + parent_info = read_node(parent) - # Include any parent classes in our list. - if pclasses = parent_info["classes"] - info["classes"] += pclasses - info["classes"].uniq! - end + # Include any parent classes in our list. + if pclasses = parent_info["classes"] + info["classes"] += pclasses + info["classes"].uniq! + end - # And inherit parameters from our parent, while preferring our own values. - if pparams = parent_info["parameters"] - # When using Hash#merge, the hash being merged in wins, and we - # want the subnode parameters to be the parent node parameters. - info["parameters"] = pparams.merge(info["parameters"]) - end + # And inherit parameters from our parent, while preferring our own values. + if pparams = parent_info["parameters"] + # When using Hash#merge, the hash being merged in wins, and we + # want the subnode parameters to be the parent node parameters. + info["parameters"] = pparams.merge(info["parameters"]) + end - # Copy over any parent node name. - if pparent = parent_info["parent"] - info["parent"] = pparent - end + # Copy over any parent node name. + if pparent = parent_info["parent"] + info["parent"] = pparent + end end puts YAML.dump(info) |