summaryrefslogtreecommitdiffstats
path: root/lib/puppet/provider
diff options
context:
space:
mode:
Diffstat (limited to 'lib/puppet/provider')
-rw-r--r--lib/puppet/provider/augeas/augeas.rb636
-rw-r--r--lib/puppet/provider/computer/computer.rb26
-rw-r--r--lib/puppet/provider/confine.rb126
-rw-r--r--lib/puppet/provider/confine/exists.rb28
-rw-r--r--lib/puppet/provider/confine/false.rb24
-rw-r--r--lib/puppet/provider/confine/feature.rb20
-rw-r--r--lib/puppet/provider/confine/true.rb26
-rw-r--r--lib/puppet/provider/confine/variable.rb102
-rw-r--r--lib/puppet/provider/confine_collection.rb76
-rw-r--r--lib/puppet/provider/confiner.rb20
-rwxr-xr-xlib/puppet/provider/cron/crontab.rb336
-rw-r--r--lib/puppet/provider/file/posix.rb146
-rw-r--r--lib/puppet/provider/file/win32.rb112
-rw-r--r--lib/puppet/provider/group/directoryservice.rb12
-rw-r--r--lib/puppet/provider/group/groupadd.rb36
-rw-r--r--lib/puppet/provider/group/ldap.rb80
-rw-r--r--lib/puppet/provider/group/pw.rb46
-rw-r--r--lib/puppet/provider/host/parsed.rb98
-rw-r--r--lib/puppet/provider/ldap.rb242
-rw-r--r--lib/puppet/provider/macauthorization/macauthorization.rb526
-rwxr-xr-xlib/puppet/provider/mailalias/aliases.rb64
-rwxr-xr-xlib/puppet/provider/maillist/mailman.rb174
-rw-r--r--lib/puppet/provider/mcx/mcxcontent.rb308
-rw-r--r--lib/puppet/provider/mount.rb72
-rwxr-xr-xlib/puppet/provider/mount/parsed.rb52
-rw-r--r--lib/puppet/provider/naginator.rb92
-rw-r--r--lib/puppet/provider/nameservice.rb430
-rw-r--r--lib/puppet/provider/nameservice/directoryservice.rb912
-rw-r--r--lib/puppet/provider/nameservice/objectadd.rb42
-rw-r--r--lib/puppet/provider/nameservice/pw.rb26
-rw-r--r--lib/puppet/provider/package.rb36
-rw-r--r--lib/puppet/provider/package/aix.rb180
-rw-r--r--lib/puppet/provider/package/appdmg.rb152
-rwxr-xr-xlib/puppet/provider/package/apple.rb74
-rwxr-xr-xlib/puppet/provider/package/apt.rb176
-rwxr-xr-xlib/puppet/provider/package/aptitude.rb38
-rw-r--r--lib/puppet/provider/package/aptrpm.rb140
-rwxr-xr-xlib/puppet/provider/package/blastwave.rb176
-rwxr-xr-xlib/puppet/provider/package/darwinport.rb134
-rwxr-xr-xlib/puppet/provider/package/dpkg.rb242
-rwxr-xr-xlib/puppet/provider/package/fink.rb132
-rwxr-xr-xlib/puppet/provider/package/freebsd.rb76
-rwxr-xr-xlib/puppet/provider/package/gem.rb196
-rw-r--r--lib/puppet/provider/package/hpux.rb74
-rw-r--r--lib/puppet/provider/package/nim.rb42
-rwxr-xr-xlib/puppet/provider/package/openbsd.rb198
-rw-r--r--lib/puppet/provider/package/pkg.rb164
-rw-r--r--lib/puppet/provider/package/pkgdmg.rb182
-rw-r--r--lib/puppet/provider/package/portage.rb200
-rwxr-xr-xlib/puppet/provider/package/ports.rb142
-rw-r--r--lib/puppet/provider/package/portupgrade.rb406
-rwxr-xr-xlib/puppet/provider/package/rpm.rb226
-rw-r--r--lib/puppet/provider/package/rug.rb92
-rwxr-xr-xlib/puppet/provider/package/sun.rb270
-rwxr-xr-xlib/puppet/provider/package/sunfreeware.rb10
-rw-r--r--lib/puppet/provider/package/up2date.rb62
-rw-r--r--lib/puppet/provider/package/urpmi.rb102
-rwxr-xr-xlib/puppet/provider/package/yum.rb178
-rw-r--r--lib/puppet/provider/package/zypper.rb92
-rwxr-xr-xlib/puppet/provider/parsedfile.rb608
-rw-r--r--lib/puppet/provider/selboolean/getsetsebool.rb70
-rw-r--r--lib/puppet/provider/selmodule/semodule.rb206
-rwxr-xr-xlib/puppet/provider/service/base.rb268
-rw-r--r--lib/puppet/provider/service/bsd.rb82
-rw-r--r--lib/puppet/provider/service/daemontools.rb314
-rwxr-xr-xlib/puppet/provider/service/debian.rb84
-rw-r--r--lib/puppet/provider/service/freebsd.rb254
-rw-r--r--lib/puppet/provider/service/gentoo.rb64
-rwxr-xr-xlib/puppet/provider/service/init.rb250
-rw-r--r--lib/puppet/provider/service/launchd.rb468
-rwxr-xr-xlib/puppet/provider/service/redhat.rb116
-rw-r--r--lib/puppet/provider/service/runit.rb160
-rwxr-xr-xlib/puppet/provider/service/smf.rb164
-rwxr-xr-xlib/puppet/provider/service/src.rb162
-rw-r--r--lib/puppet/provider/ssh_authorized_key/parsed.rb142
-rwxr-xr-xlib/puppet/provider/sshkey/parsed.rb44
-rw-r--r--lib/puppet/provider/user/directoryservice.rb142
-rw-r--r--lib/puppet/provider/user/hpux.rb40
-rw-r--r--lib/puppet/provider/user/ldap.rb212
-rw-r--r--lib/puppet/provider/user/pw.rb64
-rw-r--r--lib/puppet/provider/user/user_role_add.rb336
-rw-r--r--lib/puppet/provider/user/useradd.rb100
-rw-r--r--lib/puppet/provider/zfs/solaris.rb70
-rw-r--r--lib/puppet/provider/zone/solaris.rb414
-rw-r--r--lib/puppet/provider/zpool/solaris.rb190
85 files changed, 7053 insertions, 7053 deletions
diff --git a/lib/puppet/provider/augeas/augeas.rb b/lib/puppet/provider/augeas/augeas.rb
index 4fff9e299..7dbd06240 100644
--- a/lib/puppet/provider/augeas/augeas.rb
+++ b/lib/puppet/provider/augeas/augeas.rb
@@ -21,341 +21,341 @@ require 'augeas' if Puppet.features.augeas?
require 'strscan'
Puppet::Type.type(:augeas).provide(:augeas) do
- include Puppet::Util
-
- confine :true => Puppet.features.augeas?
-
- has_features :parse_commands, :need_to_run?,:execute_changes
-
- SAVE_NOOP = "noop"
- SAVE_OVERWRITE = "overwrite"
-
- COMMANDS = {
- "set" => [ :path, :string ],
- "rm" => [ :path ],
- "clear" => [ :path ],
- "insert" => [ :string, :string, :path ],
- "get" => [ :path, :comparator, :string ],
- "match" => [ :path, :glob ],
- "size" => [:comparator, :int],
- "include" => [:string],
- "not_include" => [:string],
- "==" => [:glob],
- "!=" => [:glob]
- }
-
- COMMANDS["ins"] = COMMANDS["insert"]
- COMMANDS["remove"] = COMMANDS["rm"]
-
- attr_accessor :aug
-
- # Extracts an 2 dimensional array of commands which are in the
- # form of command path value.
- # The input can be
- # - A string with one command
- # - A string with many commands per line
- # - An array of strings.
- def parse_commands(data)
- context = resource[:context]
- # Add a trailing / if it is not there
- if (context.length > 0)
- context << "/" if context[-1, 1] != "/"
- end
-
- data = data.split($/) if data.is_a?(String)
- data = data.flatten
- args = []
- data.each do |line|
- line.strip!
- next if line.nil? || line.empty?
- argline = []
- sc = StringScanner.new(line)
- cmd = sc.scan(/\w+|==|!=/)
- formals = COMMANDS[cmd]
- fail("Unknown command #{cmd}") unless formals
- argline << cmd
- narg = 0
- formals.each do |f|
- sc.skip(/\s+/)
- narg += 1
- if f == :path
- start = sc.pos
- nbracket = 0
- inSingleTick = false
- inDoubleTick = false
- begin
- sc.skip(/([^\]\[\s\\'"]|\\.)+/)
- ch = sc.getch
- nbracket += 1 if ch == "["
- nbracket -= 1 if ch == "]"
- inSingleTick = !inSingleTick if ch == "'"
- inDoubleTick = !inDoubleTick if ch == "\""
- fail("unmatched [") if nbracket < 0
- end until ((nbracket == 0 && !inSingleTick && !inDoubleTick && (ch =~ /\s/)) || sc.eos?)
- len = sc.pos - start
- len -= 1 unless sc.eos?
- unless p = sc.string[start, len]
- fail("missing path argument #{narg} for #{cmd}")
- end
- # Rip off any ticks if they are there.
- p = p[1, (p.size - 2)] if p[0,1] == "'" || p[0,1] == "\""
- p.chomp!("/")
- if p[0,1] != '$' && p[0,1] != "/"
- argline << context + p
- else
- argline << p
- end
- elsif f == :string
- delim = sc.peek(1)
- if delim == "'" || delim == "\""
- sc.getch
- argline << sc.scan(/([^\\#{delim}]|(\\.))*/)
- sc.getch
- else
- argline << sc.scan(/[^\s]+/)
- end
- fail("missing string argument #{narg} for #{cmd}") unless argline[-1]
- elsif f == :comparator
- argline << sc.scan(/(==|!=|=~|<|<=|>|>=)/)
- unless argline[-1]
- puts sc.rest
- fail("invalid comparator for command #{cmd}")
- end
- elsif f == :int
- argline << sc.scan(/\d+/).to_i
- elsif f== :glob
- argline << sc.rest
- end
- end
- args << argline
- end
- args
+ include Puppet::Util
+
+ confine :true => Puppet.features.augeas?
+
+ has_features :parse_commands, :need_to_run?,:execute_changes
+
+ SAVE_NOOP = "noop"
+ SAVE_OVERWRITE = "overwrite"
+
+ COMMANDS = {
+ "set" => [ :path, :string ],
+ "rm" => [ :path ],
+ "clear" => [ :path ],
+ "insert" => [ :string, :string, :path ],
+ "get" => [ :path, :comparator, :string ],
+ "match" => [ :path, :glob ],
+ "size" => [:comparator, :int],
+ "include" => [:string],
+ "not_include" => [:string],
+ "==" => [:glob],
+ "!=" => [:glob]
+ }
+
+ COMMANDS["ins"] = COMMANDS["insert"]
+ COMMANDS["remove"] = COMMANDS["rm"]
+
+ attr_accessor :aug
+
+ # Extracts an 2 dimensional array of commands which are in the
+ # form of command path value.
+ # The input can be
+ # - A string with one command
+ # - A string with many commands per line
+ # - An array of strings.
+ def parse_commands(data)
+ context = resource[:context]
+ # Add a trailing / if it is not there
+ if (context.length > 0)
+ context << "/" if context[-1, 1] != "/"
end
-
- def open_augeas
- unless @aug
- flags = Augeas::NONE
- flags = Augeas::TYPE_CHECK if resource[:type_check] == :true
- flags |= Augeas::NO_MODL_AUTOLOAD if resource[:incl]
- root = resource[:root]
- load_path = resource[:load_path]
- debug("Opening augeas with root #{root}, lens path #{load_path}, flags #{flags}")
- @aug = Augeas::open(root, load_path,flags)
-
- debug("Augeas version #{get_augeas_version} is installed") if get_augeas_version >= "0.3.6"
-
- if resource[:incl]
- aug.set("/augeas/load/Xfm/lens", resource[:lens])
- aug.set("/augeas/load/Xfm/incl", resource[:incl])
- aug.load
- end
+ data = data.split($/) if data.is_a?(String)
+ data = data.flatten
+ args = []
+ data.each do |line|
+ line.strip!
+ next if line.nil? || line.empty?
+ argline = []
+ sc = StringScanner.new(line)
+ cmd = sc.scan(/\w+|==|!=/)
+ formals = COMMANDS[cmd]
+ fail("Unknown command #{cmd}") unless formals
+ argline << cmd
+ narg = 0
+ formals.each do |f|
+ sc.skip(/\s+/)
+ narg += 1
+ if f == :path
+ start = sc.pos
+ nbracket = 0
+ inSingleTick = false
+ inDoubleTick = false
+ begin
+ sc.skip(/([^\]\[\s\\'"]|\\.)+/)
+ ch = sc.getch
+ nbracket += 1 if ch == "["
+ nbracket -= 1 if ch == "]"
+ inSingleTick = !inSingleTick if ch == "'"
+ inDoubleTick = !inDoubleTick if ch == "\""
+ fail("unmatched [") if nbracket < 0
+ end until ((nbracket == 0 && !inSingleTick && !inDoubleTick && (ch =~ /\s/)) || sc.eos?)
+ len = sc.pos - start
+ len -= 1 unless sc.eos?
+ unless p = sc.string[start, len]
+ fail("missing path argument #{narg} for #{cmd}")
+ end
+ # Rip off any ticks if they are there.
+ p = p[1, (p.size - 2)] if p[0,1] == "'" || p[0,1] == "\""
+ p.chomp!("/")
+ if p[0,1] != '$' && p[0,1] != "/"
+ argline << context + p
+ else
+ argline << p
+ end
+ elsif f == :string
+ delim = sc.peek(1)
+ if delim == "'" || delim == "\""
+ sc.getch
+ argline << sc.scan(/([^\\#{delim}]|(\\.))*/)
+ sc.getch
+ else
+ argline << sc.scan(/[^\s]+/)
+ end
+ fail("missing string argument #{narg} for #{cmd}") unless argline[-1]
+ elsif f == :comparator
+ argline << sc.scan(/(==|!=|=~|<|<=|>|>=)/)
+ unless argline[-1]
+ puts sc.rest
+ fail("invalid comparator for command #{cmd}")
+ end
+ elsif f == :int
+ argline << sc.scan(/\d+/).to_i
+ elsif f== :glob
+ argline << sc.rest
end
- @aug
+ end
+ args << argline
end
-
- def close_augeas
- if @aug
- @aug.close
- debug("Closed the augeas connection")
- @aug = nil
- end
+ args
+ end
+
+
+ def open_augeas
+ unless @aug
+ flags = Augeas::NONE
+ flags = Augeas::TYPE_CHECK if resource[:type_check] == :true
+ flags |= Augeas::NO_MODL_AUTOLOAD if resource[:incl]
+ root = resource[:root]
+ load_path = resource[:load_path]
+ debug("Opening augeas with root #{root}, lens path #{load_path}, flags #{flags}")
+ @aug = Augeas::open(root, load_path,flags)
+
+ debug("Augeas version #{get_augeas_version} is installed") if get_augeas_version >= "0.3.6"
+
+ if resource[:incl]
+ aug.set("/augeas/load/Xfm/lens", resource[:lens])
+ aug.set("/augeas/load/Xfm/incl", resource[:incl])
+ aug.load
+ end
end
-
- # Used by the need_to_run? method to process get filters. Returns
- # true if there is a match, false if otherwise
- # Assumes a syntax of get /files/path [COMPARATOR] value
- def process_get(cmd_array)
- return_value = false
-
- #validate and tear apart the command
- fail ("Invalid command: #{cmd_array.join(" ")}") if cmd_array.length < 4
- cmd = cmd_array.shift
- path = cmd_array.shift
- comparator = cmd_array.shift
- arg = cmd_array.join(" ")
-
- #check the value in augeas
- result = @aug.get(path) || ''
- case comparator
- when "!="
- return_value = (result != arg)
- when "=~"
- regex = Regexp.new(arg)
- return_value = (result =~ regex)
- else
- return_value = (result.send(comparator, arg))
- end
- !!return_value
+ @aug
+ end
+
+ def close_augeas
+ if @aug
+ @aug.close
+ debug("Closed the augeas connection")
+ @aug = nil
end
-
- # Used by the need_to_run? method to process match filters. Returns
- # true if there is a match, false if otherwise
- def process_match(cmd_array)
- return_value = false
-
- #validate and tear apart the command
- fail("Invalid command: #{cmd_array.join(" ")}") if cmd_array.length < 3
- cmd = cmd_array.shift
- path = cmd_array.shift
-
- # Need to break apart the clause
- clause_array = parse_commands(cmd_array.shift)[0]
- verb = clause_array.shift
-
- #Get the values from augeas
- result = @aug.match(path) || []
- fail("Error trying to match path '#{path}'") if (result == -1)
-
- # Now do the work
- case verb
- when "size"
- fail("Invalid command: #{cmd_array.join(" ")}") if clause_array.length != 2
- comparator = clause_array.shift
- arg = clause_array.shift
- return_value = (result.size.send(comparator, arg))
- when "include"
- arg = clause_array.shift
- return_value = result.include?(arg)
- when "not_include"
- arg = clause_array.shift
- return_value = !result.include?(arg)
- when "=="
- begin
- arg = clause_array.shift
- new_array = eval arg
- return_value = (result == new_array)
- rescue
- fail("Invalid array in command: #{cmd_array.join(" ")}")
- end
- when "!="
- begin
- arg = clause_array.shift
- new_array = eval arg
- return_value = (result != new_array)
- rescue
- fail("Invalid array in command: #{cmd_array.join(" ")}")
- end
- end
- !!return_value
- end
-
- def get_augeas_version
- @aug.get("/augeas/version") || ""
+ end
+
+ # Used by the need_to_run? method to process get filters. Returns
+ # true if there is a match, false if otherwise
+ # Assumes a syntax of get /files/path [COMPARATOR] value
+ def process_get(cmd_array)
+ return_value = false
+
+ #validate and tear apart the command
+ fail ("Invalid command: #{cmd_array.join(" ")}") if cmd_array.length < 4
+ cmd = cmd_array.shift
+ path = cmd_array.shift
+ comparator = cmd_array.shift
+ arg = cmd_array.join(" ")
+
+ #check the value in augeas
+ result = @aug.get(path) || ''
+ case comparator
+ when "!="
+ return_value = (result != arg)
+ when "=~"
+ regex = Regexp.new(arg)
+ return_value = (result =~ regex)
+ else
+ return_value = (result.send(comparator, arg))
end
-
- def set_augeas_save_mode(mode)
- @aug.set("/augeas/save", mode)
+ !!return_value
+ end
+
+ # Used by the need_to_run? method to process match filters. Returns
+ # true if there is a match, false if otherwise
+ def process_match(cmd_array)
+ return_value = false
+
+ #validate and tear apart the command
+ fail("Invalid command: #{cmd_array.join(" ")}") if cmd_array.length < 3
+ cmd = cmd_array.shift
+ path = cmd_array.shift
+
+ # Need to break apart the clause
+ clause_array = parse_commands(cmd_array.shift)[0]
+ verb = clause_array.shift
+
+ #Get the values from augeas
+ result = @aug.match(path) || []
+ fail("Error trying to match path '#{path}'") if (result == -1)
+
+ # Now do the work
+ case verb
+ when "size"
+ fail("Invalid command: #{cmd_array.join(" ")}") if clause_array.length != 2
+ comparator = clause_array.shift
+ arg = clause_array.shift
+ return_value = (result.size.send(comparator, arg))
+ when "include"
+ arg = clause_array.shift
+ return_value = result.include?(arg)
+ when "not_include"
+ arg = clause_array.shift
+ return_value = !result.include?(arg)
+ when "=="
+ begin
+ arg = clause_array.shift
+ new_array = eval arg
+ return_value = (result == new_array)
+ rescue
+ fail("Invalid array in command: #{cmd_array.join(" ")}")
+ end
+ when "!="
+ begin
+ arg = clause_array.shift
+ new_array = eval arg
+ return_value = (result != new_array)
+ rescue
+ fail("Invalid array in command: #{cmd_array.join(" ")}")
+ end
end
-
- def files_changed?
- saved_files = @aug.match("/augeas/events/saved")
- saved_files.size > 0
- end
-
- # Determines if augeas acutally needs to run.
- def need_to_run?
- force = resource[:force]
- return_value = true
+ !!return_value
+ end
+
+ def get_augeas_version
+ @aug.get("/augeas/version") || ""
+ end
+
+ def set_augeas_save_mode(mode)
+ @aug.set("/augeas/save", mode)
+ end
+
+ def files_changed?
+ saved_files = @aug.match("/augeas/events/saved")
+ saved_files.size > 0
+ end
+
+ # Determines if augeas acutally needs to run.
+ def need_to_run?
+ force = resource[:force]
+ return_value = true
+ begin
+ open_augeas
+ filter = resource[:onlyif]
+ unless filter == ""
+ cmd_array = parse_commands(filter)[0]
+ command = cmd_array[0];
begin
- open_augeas
- filter = resource[:onlyif]
- unless filter == ""
- cmd_array = parse_commands(filter)[0]
- command = cmd_array[0];
- begin
- case command
- when "get"; return_value = process_get(cmd_array)
- when "match"; return_value = process_match(cmd_array)
- end
- rescue SystemExit,NoMemoryError
- raise
- rescue Exception => e
- fail("Error sending command '#{command}' with params #{cmd_array[1..-1].inspect}/#{e.message}")
- end
- end
-
- unless force
- # If we have a verison of augeas which is at least 0.3.6 then we
- # can make the changes now, see if changes were made, and
- # actually do the save.
- if return_value and get_augeas_version >= "0.3.6"
- debug("Will attempt to save and only run if files changed")
- set_augeas_save_mode(SAVE_NOOP)
- do_execute_changes
- save_result = @aug.save
- saved_files = @aug.match("/augeas/events/saved")
- if save_result and not files_changed?
- debug("Skipping because no files were changed")
- return_value = false
- else
- debug("Files changed, should execute")
- end
- end
- end
- ensure
- close_augeas
+ case command
+ when "get"; return_value = process_get(cmd_array)
+ when "match"; return_value = process_match(cmd_array)
+ end
+ rescue SystemExit,NoMemoryError
+ raise
+ rescue Exception => e
+ fail("Error sending command '#{command}' with params #{cmd_array[1..-1].inspect}/#{e.message}")
+ end
+ end
+
+ unless force
+ # If we have a verison of augeas which is at least 0.3.6 then we
+ # can make the changes now, see if changes were made, and
+ # actually do the save.
+ if return_value and get_augeas_version >= "0.3.6"
+ debug("Will attempt to save and only run if files changed")
+ set_augeas_save_mode(SAVE_NOOP)
+ do_execute_changes
+ save_result = @aug.save
+ saved_files = @aug.match("/augeas/events/saved")
+ if save_result and not files_changed?
+ debug("Skipping because no files were changed")
+ return_value = false
+ else
+ debug("Files changed, should execute")
+ end
end
- return_value
+ end
+ ensure
+ close_augeas
end
+ return_value
+ end
- def execute_changes
- # Re-connect to augeas, and re-execute the changes
- begin
- open_augeas
- set_augeas_save_mode(SAVE_OVERWRITE) if get_augeas_version >= "0.3.6"
-
- do_execute_changes
+ def execute_changes
+ # Re-connect to augeas, and re-execute the changes
+ begin
+ open_augeas
+ set_augeas_save_mode(SAVE_OVERWRITE) if get_augeas_version >= "0.3.6"
- success = @aug.save
- fail("Save failed with return code #{success}") if success != true
- ensure
- close_augeas
- end
+ do_execute_changes
- :executed
+ success = @aug.save
+ fail("Save failed with return code #{success}") if success != true
+ ensure
+ close_augeas
end
- # Actually execute the augeas changes.
- def do_execute_changes
- commands = parse_commands(resource[:changes])
- commands.each do |cmd_array|
- fail("invalid command #{cmd_array.join[" "]}") if cmd_array.length < 2
- command = cmd_array[0]
- cmd_array.shift
- begin
- case command
- when "set"
- debug("sending command '#{command}' with params #{cmd_array.inspect}")
- rv = aug.set(cmd_array[0], cmd_array[1])
- fail("Error sending command '#{command}' with params #{cmd_array.inspect}") if (!rv)
- when "rm", "remove"
- debug("sending command '#{command}' with params #{cmd_array.inspect}")
- rv = aug.rm(cmd_array[0])
- fail("Error sending command '#{command}' with params #{cmd_array.inspect}") if (rv == -1)
- when "clear"
- debug("sending command '#{command}' with params #{cmd_array.inspect}")
- rv = aug.clear(cmd_array[0])
- fail("Error sending command '#{command}' with params #{cmd_array.inspect}") if (!rv)
- when "insert", "ins"
- label = cmd_array[0]
- where = cmd_array[1]
- path = cmd_array[2]
- case where
- when "before"; before = true
- when "after"; before = false
- else fail("Invalid value '#{where}' for where param")
- end
- debug("sending command '#{command}' with params #{[label, where, path].inspect}")
- rv = aug.insert(path, label, before)
- fail("Error sending command '#{command}' with params #{cmd_array.inspect}") if (rv == -1)
- else fail("Command '#{command}' is not supported")
- end
- rescue SystemExit,NoMemoryError
- raise
- rescue Exception => e
- fail("Error sending command '#{command}' with params #{cmd_array.inspect}/#{e.message}")
+ :executed
+ end
+
+ # Actually execute the augeas changes.
+ def do_execute_changes
+ commands = parse_commands(resource[:changes])
+ commands.each do |cmd_array|
+ fail("invalid command #{cmd_array.join[" "]}") if cmd_array.length < 2
+ command = cmd_array[0]
+ cmd_array.shift
+ begin
+ case command
+ when "set"
+ debug("sending command '#{command}' with params #{cmd_array.inspect}")
+ rv = aug.set(cmd_array[0], cmd_array[1])
+ fail("Error sending command '#{command}' with params #{cmd_array.inspect}") if (!rv)
+ when "rm", "remove"
+ debug("sending command '#{command}' with params #{cmd_array.inspect}")
+ rv = aug.rm(cmd_array[0])
+ fail("Error sending command '#{command}' with params #{cmd_array.inspect}") if (rv == -1)
+ when "clear"
+ debug("sending command '#{command}' with params #{cmd_array.inspect}")
+ rv = aug.clear(cmd_array[0])
+ fail("Error sending command '#{command}' with params #{cmd_array.inspect}") if (!rv)
+ when "insert", "ins"
+ label = cmd_array[0]
+ where = cmd_array[1]
+ path = cmd_array[2]
+ case where
+ when "before"; before = true
+ when "after"; before = false
+ else fail("Invalid value '#{where}' for where param")
end
+ debug("sending command '#{command}' with params #{[label, where, path].inspect}")
+ rv = aug.insert(path, label, before)
+ fail("Error sending command '#{command}' with params #{cmd_array.inspect}") if (rv == -1)
+ else fail("Command '#{command}' is not supported")
end
+ rescue SystemExit,NoMemoryError
+ raise
+ rescue Exception => e
+ fail("Error sending command '#{command}' with params #{cmd_array.inspect}/#{e.message}")
+ end
end
+ end
end
diff --git a/lib/puppet/provider/computer/computer.rb b/lib/puppet/provider/computer/computer.rb
index 73f2d2b89..a6be6bdfe 100644
--- a/lib/puppet/provider/computer/computer.rb
+++ b/lib/puppet/provider/computer/computer.rb
@@ -1,22 +1,22 @@
require 'puppet/provider/nameservice/directoryservice'
Puppet::Type.type(:computer).provide :directoryservice, :parent => Puppet::Provider::NameService::DirectoryService do
- desc "Computer object management using DirectoryService on OS X.
- Note that these are distinctly different kinds of objects to 'hosts',
- as they require a MAC address and can have all sorts of policy attached to
- them.
+ desc "Computer object management using DirectoryService on OS X.
+ Note that these are distinctly different kinds of objects to 'hosts',
+ as they require a MAC address and can have all sorts of policy attached to
+ them.
- This provider only manages Computer objects in the local directory service
- domain, not in remote directories.
+ This provider only manages Computer objects in the local directory service
+ domain, not in remote directories.
- If you wish to manage /etc/hosts on Mac OS X, then simply use the host
- type as per other platforms.
+ If you wish to manage /etc/hosts on Mac OS X, then simply use the host
+ type as per other platforms.
- "
+ "
- confine :operatingsystem => :darwin
- defaultfor :operatingsystem => :darwin
+ confine :operatingsystem => :darwin
+ defaultfor :operatingsystem => :darwin
- # hurray for abstraction. The nameservice directoryservice provider can
- # handle everything we need. super.
+ # hurray for abstraction. The nameservice directoryservice provider can
+ # handle everything we need. super.
end
diff --git a/lib/puppet/provider/confine.rb b/lib/puppet/provider/confine.rb
index e75bc5c78..6825def7e 100644
--- a/lib/puppet/provider/confine.rb
+++ b/lib/puppet/provider/confine.rb
@@ -3,78 +3,78 @@
require 'puppet/util'
class Puppet::Provider::Confine
- include Puppet::Util
+ include Puppet::Util
- @tests = {}
+ @tests = {}
- class << self
- attr_accessor :name
- end
+ class << self
+ attr_accessor :name
+ end
- def self.inherited(klass)
- name = klass.to_s.split("::").pop.downcase.to_sym
- raise "Test #{name} is already defined" if @tests.include?(name)
+ def self.inherited(klass)
+ name = klass.to_s.split("::").pop.downcase.to_sym
+ raise "Test #{name} is already defined" if @tests.include?(name)
- klass.name = name
+ klass.name = name
- @tests[name] = klass
- end
+ @tests[name] = klass
+ end
- def self.test(name)
- unless @tests[name]
- begin
- require "puppet/provider/confine/#{name}"
- rescue LoadError => detail
- unless detail.to_s =~ /No such file/i
- warn "Could not load confine test '#{name}': #{detail}"
- end
- # Could not find file
- end
+ def self.test(name)
+ unless @tests[name]
+ begin
+ require "puppet/provider/confine/#{name}"
+ rescue LoadError => detail
+ unless detail.to_s =~ /No such file/i
+ warn "Could not load confine test '#{name}': #{detail}"
end
- @tests[name]
- end
-
- attr_reader :values
-
- # Mark that this confine is used for testing binary existence.
- attr_accessor :for_binary
- def for_binary?
- for_binary
+ # Could not find file
+ end
end
-
- # Used for logging.
- attr_accessor :label
-
- def initialize(values)
- values = [values] unless values.is_a?(Array)
- @values = values
+ @tests[name]
+ end
+
+ attr_reader :values
+
+ # Mark that this confine is used for testing binary existence.
+ attr_accessor :for_binary
+ def for_binary?
+ for_binary
+ end
+
+ # Used for logging.
+ attr_accessor :label
+
+ def initialize(values)
+ values = [values] unless values.is_a?(Array)
+ @values = values
+ end
+
+ # Provide a hook for the message when there's a failure.
+ def message(value)
+ ""
+ end
+
+ # Collect the results of all of them.
+ def result
+ values.collect { |value| pass?(value) }
+ end
+
+ # Test whether our confine matches.
+ def valid?
+ values.each do |value|
+ unless pass?(value)
+ Puppet.debug(label + ": " + message(value))
+ return false
+ end
end
- # Provide a hook for the message when there's a failure.
- def message(value)
- ""
- end
+ return true
+ ensure
+ reset
+ end
- # Collect the results of all of them.
- def result
- values.collect { |value| pass?(value) }
- end
-
- # Test whether our confine matches.
- def valid?
- values.each do |value|
- unless pass?(value)
- Puppet.debug(label + ": " + message(value))
- return false
- end
- end
-
- return true
- ensure
- reset
- end
-
- # Provide a hook for subclasses.
- def reset
- end
+ # Provide a hook for subclasses.
+ def reset
+ end
end
diff --git a/lib/puppet/provider/confine/exists.rb b/lib/puppet/provider/confine/exists.rb
index 27c404acb..085118b2a 100644
--- a/lib/puppet/provider/confine/exists.rb
+++ b/lib/puppet/provider/confine/exists.rb
@@ -1,22 +1,22 @@
require 'puppet/provider/confine'
class Puppet::Provider::Confine::Exists < Puppet::Provider::Confine
- def self.summarize(confines)
- confines.inject([]) { |total, confine| total + confine.summary }
- end
+ def self.summarize(confines)
+ confines.inject([]) { |total, confine| total + confine.summary }
+ end
- def pass?(value)
- if for_binary?
- return false unless value = binary(value)
- end
- value and FileTest.exist?(value)
+ def pass?(value)
+ if for_binary?
+ return false unless value = binary(value)
end
+ value and FileTest.exist?(value)
+ end
- def message(value)
- "file #{value} does not exist"
- end
+ def message(value)
+ "file #{value} does not exist"
+ end
- def summary
- result.zip(values).inject([]) { |array, args| val, f = args; array << f unless val; array }
- end
+ def summary
+ result.zip(values).inject([]) { |array, args| val, f = args; array << f unless val; array }
+ end
end
diff --git a/lib/puppet/provider/confine/false.rb b/lib/puppet/provider/confine/false.rb
index b5b2b51c8..1c11dd40f 100644
--- a/lib/puppet/provider/confine/false.rb
+++ b/lib/puppet/provider/confine/false.rb
@@ -1,19 +1,19 @@
require 'puppet/provider/confine'
class Puppet::Provider::Confine::False < Puppet::Provider::Confine
- def self.summarize(confines)
- confines.inject(0) { |count, confine| count + confine.summary }
- end
+ def self.summarize(confines)
+ confines.inject(0) { |count, confine| count + confine.summary }
+ end
- def pass?(value)
- ! value
- end
+ def pass?(value)
+ ! value
+ end
- def message(value)
- "true value when expecting false"
- end
+ def message(value)
+ "true value when expecting false"
+ end
- def summary
- result.find_all { |v| v == false }.length
- end
+ def summary
+ result.find_all { |v| v == false }.length
+ end
end
diff --git a/lib/puppet/provider/confine/feature.rb b/lib/puppet/provider/confine/feature.rb
index 8cd5daaec..b223b8b11 100644
--- a/lib/puppet/provider/confine/feature.rb
+++ b/lib/puppet/provider/confine/feature.rb
@@ -1,17 +1,17 @@
require 'puppet/provider/confine'
class Puppet::Provider::Confine::Feature < Puppet::Provider::Confine
- def self.summarize(confines)
- confines.collect { |c| c.values }.flatten.uniq.find_all { |value| ! confines[0].pass?(value) }
- end
+ def self.summarize(confines)
+ confines.collect { |c| c.values }.flatten.uniq.find_all { |value| ! confines[0].pass?(value) }
+ end
- # Is the named feature available?
- def pass?(value)
- Puppet.features.send(value.to_s + "?")
- end
+ # Is the named feature available?
+ def pass?(value)
+ Puppet.features.send(value.to_s + "?")
+ end
- def message(value)
- "feature #{value} is missing"
- end
+ def message(value)
+ "feature #{value} is missing"
+ end
end
diff --git a/lib/puppet/provider/confine/true.rb b/lib/puppet/provider/confine/true.rb
index 86b3b144f..559f2675f 100644
--- a/lib/puppet/provider/confine/true.rb
+++ b/lib/puppet/provider/confine/true.rb
@@ -1,20 +1,20 @@
require 'puppet/provider/confine'
class Puppet::Provider::Confine::True < Puppet::Provider::Confine
- def self.summarize(confines)
- confines.inject(0) { |count, confine| count + confine.summary }
- end
+ def self.summarize(confines)
+ confines.inject(0) { |count, confine| count + confine.summary }
+ end
- def pass?(value)
- # Double negate, so we only get true or false.
- ! ! value
- end
+ def pass?(value)
+ # Double negate, so we only get true or false.
+ ! ! value
+ end
- def message(value)
- "false value when expecting true"
- end
+ def message(value)
+ "false value when expecting true"
+ end
- def summary
- result.find_all { |v| v == true }.length
- end
+ def summary
+ result.find_all { |v| v == true }.length
+ end
end
diff --git a/lib/puppet/provider/confine/variable.rb b/lib/puppet/provider/confine/variable.rb
index 84f7e4044..af8e5d314 100644
--- a/lib/puppet/provider/confine/variable.rb
+++ b/lib/puppet/provider/confine/variable.rb
@@ -5,55 +5,55 @@ require 'puppet/provider/confine'
# is set explicitly by the ConfineCollection class -- from this class,
# it's not obvious how the name would ever get set.
class Puppet::Provider::Confine::Variable < Puppet::Provider::Confine
- # Provide a hash summary of failing confines -- the key of the hash
- # is the name of the confine, and the value is the missing yet required values.
- # Only returns failed values, not all required values.
- def self.summarize(confines)
- result = Hash.new { |hash, key| hash[key] = [] }
- confines.inject(result) { |total, confine| total[confine.name] += confine.values unless confine.valid?; total }
- end
-
- # This is set by ConfineCollection.
- attr_accessor :name
-
- # Retrieve the value from facter
- def facter_value
- @facter_value ||= ::Facter.value(name).to_s.downcase
- end
-
- def initialize(values)
- super
- @values = @values.collect { |v| v.to_s.downcase }
- end
-
- def message(value)
- "facter value '#{test_value}' for '#{self.name}' not in required list '#{values.join(",")}'"
- end
-
- # Compare the passed-in value to the retrieved value.
- def pass?(value)
- test_value.downcase.to_s == value.to_s.downcase
- end
-
- def reset
- # Reset the cache. We want to cache it during a given
- # run, but not across runs.
- @facter_value = nil
- end
-
- def valid?
- @values.include?(test_value.to_s.downcase)
- ensure
- reset
- end
-
- private
-
- def setting?
- Puppet.settings.valid?(name)
- end
-
- def test_value
- setting? ? Puppet.settings[name] : facter_value
- end
+ # Provide a hash summary of failing confines -- the key of the hash
+ # is the name of the confine, and the value is the missing yet required values.
+ # Only returns failed values, not all required values.
+ def self.summarize(confines)
+ result = Hash.new { |hash, key| hash[key] = [] }
+ confines.inject(result) { |total, confine| total[confine.name] += confine.values unless confine.valid?; total }
+ end
+
+ # This is set by ConfineCollection.
+ attr_accessor :name
+
+ # Retrieve the value from facter
+ def facter_value
+ @facter_value ||= ::Facter.value(name).to_s.downcase
+ end
+
+ def initialize(values)
+ super
+ @values = @values.collect { |v| v.to_s.downcase }
+ end
+
+ def message(value)
+ "facter value '#{test_value}' for '#{self.name}' not in required list '#{values.join(",")}'"
+ end
+
+ # Compare the passed-in value to the retrieved value.
+ def pass?(value)
+ test_value.downcase.to_s == value.to_s.downcase
+ end
+
+ def reset
+ # Reset the cache. We want to cache it during a given
+ # run, but not across runs.
+ @facter_value = nil
+ end
+
+ def valid?
+ @values.include?(test_value.to_s.downcase)
+ ensure
+ reset
+ end
+
+ private
+
+ def setting?
+ Puppet.settings.valid?(name)
+ end
+
+ def test_value
+ setting? ? Puppet.settings[name] : facter_value
+ end
end
diff --git a/lib/puppet/provider/confine_collection.rb b/lib/puppet/provider/confine_collection.rb
index 0dbdc7790..46fd3baaf 100644
--- a/lib/puppet/provider/confine_collection.rb
+++ b/lib/puppet/provider/confine_collection.rb
@@ -3,48 +3,48 @@
require 'puppet/provider/confine'
class Puppet::Provider::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|
- if klass = Puppet::Provider::Confine.test(test)
- @confines << klass.new(values)
- @confines[-1].for_binary = true if for_binary
- else
- confine = Puppet::Provider::Confine.test(:variable).new(values)
- confine.name = test
- @confines << confine
- end
- @confines[-1].label = self.label
- end
+ def confine(hash)
+ if hash.include?(:for_binary)
+ for_binary = true
+ hash.delete(:for_binary)
+ else
+ for_binary = false
end
-
- attr_reader :label
- def initialize(label)
- @label = label
- @confines = []
+ hash.each do |test, values|
+ if klass = Puppet::Provider::Confine.test(test)
+ @confines << klass.new(values)
+ @confines[-1].for_binary = true if for_binary
+ else
+ confine = Puppet::Provider::Confine.test(:variable).new(values)
+ confine.name = test
+ @confines << confine
+ end
+ @confines[-1].label = self.label
end
+ 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
+ attr_reader :label
+ def initialize(label)
+ @label = label
+ @confines = []
+ end
- end
- result
- 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
- def valid?
- ! @confines.detect { |c| ! c.valid? }
end
+ result
+ end
+
+ def valid?
+ ! @confines.detect { |c| ! c.valid? }
+ end
end
diff --git a/lib/puppet/provider/confiner.rb b/lib/puppet/provider/confiner.rb
index d776b689d..6e1fb23ab 100644
--- a/lib/puppet/provider/confiner.rb
+++ b/lib/puppet/provider/confiner.rb
@@ -1,16 +1,16 @@
require 'puppet/provider/confine_collection'
module Puppet::Provider::Confiner
- def confine(hash)
- confine_collection.confine(hash)
- end
+ def confine(hash)
+ confine_collection.confine(hash)
+ end
- def confine_collection
- @confine_collection ||= Puppet::Provider::ConfineCollection.new(self.to_s)
- end
+ def confine_collection
+ @confine_collection ||= Puppet::Provider::ConfineCollection.new(self.to_s)
+ end
- # Check whether this implementation is suitable for our platform.
- def suitable?(short = true)
- return(short ? confine_collection.valid? : confine_collection.summary)
- end
+ # Check whether this implementation is suitable for our platform.
+ def suitable?(short = true)
+ return(short ? confine_collection.valid? : confine_collection.summary)
+ end
end
diff --git a/lib/puppet/provider/cron/crontab.rb b/lib/puppet/provider/cron/crontab.rb
index 7dd41c642..8a347b331 100755
--- a/lib/puppet/provider/cron/crontab.rb
+++ b/lib/puppet/provider/cron/crontab.rb
@@ -1,206 +1,206 @@
require 'puppet/provider/parsedfile'
tab = case Facter.value(:operatingsystem)
- when "Solaris"
- :suntab
- when "AIX"
- :aixtab
- else
- :crontab
- end
+ when "Solaris"
+ :suntab
+ when "AIX"
+ :aixtab
+ else
+ :crontab
+ end
- Puppet::Type.type(:cron).provide(
- :crontab,
- :parent => Puppet::Provider::ParsedFile,
- :default_target => ENV["USER"] || "root",
+ Puppet::Type.type(:cron).provide(
+ :crontab,
+ :parent => Puppet::Provider::ParsedFile,
+ :default_target => ENV["USER"] || "root",
- :filetype => tab
+ :filetype => tab
) do
- commands :crontab => "crontab"
+ commands :crontab => "crontab"
- text_line :comment, :match => %r{^#}, :post_parse => proc { |record|
- record[:name] = $1 if record[:line] =~ /Puppet Name: (.+)\s*$/
- }
+ text_line :comment, :match => %r{^#}, :post_parse => proc { |record|
+ record[:name] = $1 if record[:line] =~ /Puppet Name: (.+)\s*$/
+ }
- text_line :blank, :match => %r{^\s*$}
+ text_line :blank, :match => %r{^\s*$}
- text_line :environment, :match => %r{^\w+=}
+ text_line :environment, :match => %r{^\w+=}
- record_line :freebsd_special, :fields => %w{special command},
- :match => %r{^@(\w+)\s+(.+)$}, :pre_gen => proc { |record|
- record[:special] = "@" + record[:special]
- }
+ record_line :freebsd_special, :fields => %w{special command},
+ :match => %r{^@(\w+)\s+(.+)$}, :pre_gen => proc { |record|
+ record[:special] = "@" + record[:special]
+ }
- crontab = record_line :crontab, :fields => %w{minute hour monthday month weekday command},
- :match => %r{^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)$},
- :optional => %w{minute hour weekday month monthday}, :absent => "*"
+ crontab = record_line :crontab, :fields => %w{minute hour monthday month weekday command},
+ :match => %r{^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)$},
+ :optional => %w{minute hour weekday month monthday}, :absent => "*"
- class << crontab
- def numeric_fields
- fields - [:command]
- end
- # Do some post-processing of the parsed record. Basically just
- # split the numeric fields on ','.
- def post_parse(record)
- numeric_fields.each do |field|
- if val = record[field] and val != :absent
- record[field] = record[field].split(",")
- end
- end
+ class << crontab
+ def numeric_fields
+ fields - [:command]
+ end
+ # Do some post-processing of the parsed record. Basically just
+ # split the numeric fields on ','.
+ def post_parse(record)
+ numeric_fields.each do |field|
+ if val = record[field] and val != :absent
+ record[field] = record[field].split(",")
end
+ end
+ end
- # Join the fields back up based on ','.
- def pre_gen(record)
- numeric_fields.each do |field|
- if vals = record[field] and vals.is_a?(Array)
- record[field] = vals.join(",")
- end
- end
+ # Join the fields back up based on ','.
+ def pre_gen(record)
+ numeric_fields.each do |field|
+ if vals = record[field] and vals.is_a?(Array)
+ record[field] = vals.join(",")
end
+ end
+ end
- # Add name and environments as necessary.
- def to_line(record)
- str = ""
- str = "# Puppet Name: #{record[:name]}\n" if record[:name]
- if record[:environment] and record[:environment] != :absent and record[:environment] != [:absent]
- record[:environment].each do |env|
- str += env + "\n"
- end
- end
-
- if record[:special]
- str += "@#{record[:special]} #{record[:command]}"
- else
- str += join(record)
- end
- str
+ # Add name and environments as necessary.
+ def to_line(record)
+ str = ""
+ str = "# Puppet Name: #{record[:name]}\n" if record[:name]
+ if record[:environment] and record[:environment] != :absent and record[:environment] != [:absent]
+ record[:environment].each do |env|
+ str += env + "\n"
end
+ end
+
+ if record[:special]
+ str += "@#{record[:special]} #{record[:command]}"
+ else
+ str += join(record)
+ end
+ str
end
+ end
- # Return the header placed at the top of each generated file, warning
- # users that modifying this file manually is probably a bad idea.
- def self.header
+ # Return the header placed at the top of each generated file, warning
+ # users that modifying this file manually is probably a bad idea.
+ def self.header
%{# HEADER: This file was autogenerated at #{Time.now} by puppet.
# HEADER: While it can still be managed manually, it is definitely not recommended.
# HEADER: Note particularly that the comments starting with 'Puppet Name' should
# HEADER: not be deleted, as doing so could cause duplicate cron jobs.\n}
- end
-
- # See if we can match the record against an existing cron job.
- def self.match(record, resources)
- resources.each do |name, resource|
- # Match the command first, since it's the most important one.
- next unless record[:target] == resource.value(:target)
- next unless record[:command] == resource.value(:command)
-
- # Then check the @special stuff
- if record[:special]
- next unless resource.value(:special) == record[:special]
- end
-
- # Then the normal fields.
- matched = true
- record_type(record[:record_type]).fields.each do |field|
- next if field == :command
- next if field == :special
- if record[field] and ! resource.value(field)
- #Puppet.info "Cron is missing %s: %s and %s" %
- # [field, record[field].inspect, resource.value(field).inspect]
- matched = false
- break
- end
-
- if ! record[field] and resource.value(field)
- #Puppet.info "Hash is missing %s: %s and %s" %
- # [field, resource.value(field).inspect, record[field].inspect]
- matched = false
- break
- end
-
- # Yay differing definitions of absent.
- next if (record[field] == :absent and resource.value(field) == "*")
-
- # Everything should be in the form of arrays, not the normal text.
- next if (record[field] == resource.value(field))
- #Puppet.info "Did not match %s: %s vs %s" %
- # [field, resource.value(field).inspect, record[field].inspect]
- matched = false
- break
- end
- return resource if matched
+ end
+
+ # See if we can match the record against an existing cron job.
+ def self.match(record, resources)
+ resources.each do |name, resource|
+ # Match the command first, since it's the most important one.
+ next unless record[:target] == resource.value(:target)
+ next unless record[:command] == resource.value(:command)
+
+ # Then check the @special stuff
+ if record[:special]
+ next unless resource.value(:special) == record[:special]
+ end
+
+ # Then the normal fields.
+ matched = true
+ record_type(record[:record_type]).fields.each do |field|
+ next if field == :command
+ next if field == :special
+ if record[field] and ! resource.value(field)
+ #Puppet.info "Cron is missing %s: %s and %s" %
+ # [field, record[field].inspect, resource.value(field).inspect]
+ matched = false
+ break
end
- false
- end
+ if ! record[field] and resource.value(field)
+ #Puppet.info "Hash is missing %s: %s and %s" %
+ # [field, resource.value(field).inspect, record[field].inspect]
+ matched = false
+ break
+ end
- # Collapse name and env records.
- def self.prefetch_hook(records)
- name = nil
- envs = nil
- result = records.each { |record|
- case record[:record_type]
- when :comment
- if record[:name]
- name = record[:name]
- record[:skip] = true
-
- # Start collecting env values
- envs = []
- end
- when :environment
- # If we're collecting env values (meaning we're in a named cronjob),
- # store the line and skip the record.
- if envs
- envs << record[:line]
- record[:skip] = true
- end
- when :blank
- # nothing
- else
- if name
- record[:name] = name
- name = nil
- end
- if envs.nil? or envs.empty?
- record[:environment] = :absent
- else
- # Collect all of the environment lines, and mark the records to be skipped,
- # since their data is included in our crontab record.
- record[:environment] = envs
-
- # And turn off env collection again
- envs = nil
- end
- end
- }.reject { |record| record[:skip] }
- result
+ # Yay differing definitions of absent.
+ next if (record[field] == :absent and resource.value(field) == "*")
+
+ # Everything should be in the form of arrays, not the normal text.
+ next if (record[field] == resource.value(field))
+ #Puppet.info "Did not match %s: %s vs %s" %
+ # [field, resource.value(field).inspect, record[field].inspect]
+ matched = false
+ break
+ end
+ return resource if matched
end
- def self.to_file(records)
- text = super
- # Apparently Freebsd will "helpfully" add a new TZ line to every
- # single cron line, but not in all cases (e.g., it doesn't do it
- # on my machine). This is my attempt to fix it so the TZ lines don't
- # multiply.
- if text =~ /(^TZ=.+\n)/
- tz = $1
- text.sub!(tz, '')
- text = tz + text
+ false
+ end
+
+ # Collapse name and env records.
+ def self.prefetch_hook(records)
+ name = nil
+ envs = nil
+ result = records.each { |record|
+ case record[:record_type]
+ when :comment
+ if record[:name]
+ name = record[:name]
+ record[:skip] = true
+
+ # Start collecting env values
+ envs = []
+ end
+ when :environment
+ # If we're collecting env values (meaning we're in a named cronjob),
+ # store the line and skip the record.
+ if envs
+ envs << record[:line]
+ record[:skip] = true
end
- text
+ when :blank
+ # nothing
+ else
+ if name
+ record[:name] = name
+ name = nil
+ end
+ if envs.nil? or envs.empty?
+ record[:environment] = :absent
+ else
+ # Collect all of the environment lines, and mark the records to be skipped,
+ # since their data is included in our crontab record.
+ record[:environment] = envs
+
+ # And turn off env collection again
+ envs = nil
+ end
+ end
+ }.reject { |record| record[:skip] }
+ result
+ end
+
+ def self.to_file(records)
+ text = super
+ # Apparently Freebsd will "helpfully" add a new TZ line to every
+ # single cron line, but not in all cases (e.g., it doesn't do it
+ # on my machine). This is my attempt to fix it so the TZ lines don't
+ # multiply.
+ if text =~ /(^TZ=.+\n)/
+ tz = $1
+ text.sub!(tz, '')
+ text = tz + text
end
+ text
+ end
- def user=(user)
- @property_hash[:user] = user
- @property_hash[:target] = user
- end
+ def user=(user)
+ @property_hash[:user] = user
+ @property_hash[:target] = user
+ end
- def user
- @property_hash[:user] || @property_hash[:target]
- end
+ def user
+ @property_hash[:user] || @property_hash[:target]
+ end
end
diff --git a/lib/puppet/provider/file/posix.rb b/lib/puppet/provider/file/posix.rb
index d715d8802..6cbf98e9a 100644
--- a/lib/puppet/provider/file/posix.rb
+++ b/lib/puppet/provider/file/posix.rb
@@ -1,99 +1,99 @@
Puppet::Type.type(:file).provide :posix do
- desc "Uses POSIX functionality to manage file's users and rights."
+ desc "Uses POSIX functionality to manage file's users and rights."
- confine :feature => :posix
+ confine :feature => :posix
- include Puppet::Util::POSIX
- include Puppet::Util::Warnings
+ include Puppet::Util::POSIX
+ include Puppet::Util::Warnings
- require 'etc'
+ require 'etc'
- def id2name(id)
- return id.to_s if id.is_a?(Symbol)
- return nil if id > Puppet[:maximum_uid].to_i
+ def id2name(id)
+ return id.to_s if id.is_a?(Symbol)
+ return nil if id > Puppet[:maximum_uid].to_i
- begin
- user = Etc.getpwuid(id)
- rescue TypeError
- return nil
- rescue ArgumentError
- return nil
- end
-
- if user.uid == ""
- return nil
- else
- return user.name
- end
+ begin
+ user = Etc.getpwuid(id)
+ rescue TypeError
+ return nil
+ rescue ArgumentError
+ return nil
end
- def insync?(current, should)
- return true unless should
-
- should.each do |value|
- if value =~ /^\d+$/
- uid = Integer(value)
- elsif value.is_a?(String)
- fail "Could not find user #{value}" unless uid = uid(value)
- else
- uid = value
- end
+ if user.uid == ""
+ return nil
+ else
+ return user.name
+ end
+ end
- return true if uid == current
- end
+ def insync?(current, should)
+ return true unless should
- unless Puppet.features.root?
- warnonce "Cannot manage ownership unless running as root"
- return true
- end
+ should.each do |value|
+ if value =~ /^\d+$/
+ uid = Integer(value)
+ elsif value.is_a?(String)
+ fail "Could not find user #{value}" unless uid = uid(value)
+ else
+ uid = value
+ end
- false
+ return true if uid == current
end
- # Determine if the user is valid, and if so, return the UID
- def validuser?(value)
- Integer(value) rescue uid(value) || false
+ unless Puppet.features.root?
+ warnonce "Cannot manage ownership unless running as root"
+ return true
end
- def retrieve(resource)
- unless stat = resource.stat(false)
- return :absent
- end
+ false
+ end
+
+ # Determine if the user is valid, and if so, return the UID
+ def validuser?(value)
+ Integer(value) rescue uid(value) || false
+ end
- currentvalue = stat.uid
+ def retrieve(resource)
+ unless stat = resource.stat(false)
+ return :absent
+ end
- # On OS X, files that are owned by -2 get returned as really
- # large UIDs instead of negative ones. This isn't a Ruby bug,
- # it's an OS X bug, since it shows up in perl, too.
- if currentvalue > Puppet[:maximum_uid].to_i
- self.warning "Apparently using negative UID (#{currentvalue}) on a platform that does not consistently handle them"
- currentvalue = :silly
- end
+ currentvalue = stat.uid
- currentvalue
+ # On OS X, files that are owned by -2 get returned as really
+ # large UIDs instead of negative ones. This isn't a Ruby bug,
+ # it's an OS X bug, since it shows up in perl, too.
+ if currentvalue > Puppet[:maximum_uid].to_i
+ self.warning "Apparently using negative UID (#{currentvalue}) on a platform that does not consistently handle them"
+ currentvalue = :silly
end
- def sync(path, links, should)
- # Set our method appropriately, depending on links.
- if links == :manage
- method = :lchown
- else
- method = :chown
- end
+ currentvalue
+ end
- uid = nil
- should.each do |user|
- break if uid = validuser?(user)
- end
+ def sync(path, links, should)
+ # Set our method appropriately, depending on links.
+ if links == :manage
+ method = :lchown
+ else
+ method = :chown
+ end
- raise Puppet::Error, "Could not find user(s) #{should.join(",")}" unless uid
+ uid = nil
+ should.each do |user|
+ break if uid = validuser?(user)
+ end
- begin
- File.send(method, uid, nil, path)
- rescue => detail
- raise Puppet::Error, "Failed to set owner to '#{uid}': #{detail}"
- end
+ raise Puppet::Error, "Could not find user(s) #{should.join(",")}" unless uid
- :file_changed
+ begin
+ File.send(method, uid, nil, path)
+ rescue => detail
+ raise Puppet::Error, "Failed to set owner to '#{uid}': #{detail}"
end
+
+ :file_changed
+ end
end
diff --git a/lib/puppet/provider/file/win32.rb b/lib/puppet/provider/file/win32.rb
index 93274ce0a..8ead69a89 100644
--- a/lib/puppet/provider/file/win32.rb
+++ b/lib/puppet/provider/file/win32.rb
@@ -1,74 +1,74 @@
Puppet::Type.type(:file).provide :microsoft_windows do
- desc "Uses Microsoft Windows functionality to manage file's users and rights."
+ desc "Uses Microsoft Windows functionality to manage file's users and rights."
- confine :feature => :microsoft_windows
+ confine :feature => :microsoft_windows
- include Puppet::Util::Warnings
+ include Puppet::Util::Warnings
- require 'sys/admin' if Puppet.features.microsoft_windows?
+ require 'sys/admin' if Puppet.features.microsoft_windows?
- def id2name(id)
- return id.to_s if id.is_a?(Symbol)
- return nil if id > Puppet[:maximum_uid].to_i
- # should translate ID numbers to usernames
- id
- end
-
- def insync?(current, should)
- return true unless should
+ def id2name(id)
+ return id.to_s if id.is_a?(Symbol)
+ return nil if id > Puppet[:maximum_uid].to_i
+ # should translate ID numbers to usernames
+ id
+ end
- should.each do |value|
- if value =~ /^\d+$/
- uid = Integer(value)
- elsif value.is_a?(String)
- fail "Could not find user #{value}" unless uid = uid(value)
- else
- uid = value
- end
+ def insync?(current, should)
+ return true unless should
- return true if uid == current
- end
+ should.each do |value|
+ if value =~ /^\d+$/
+ uid = Integer(value)
+ elsif value.is_a?(String)
+ fail "Could not find user #{value}" unless uid = uid(value)
+ else
+ uid = value
+ end
- unless Puppet.features.root?
- warnonce "Cannot manage ownership unless running as root"
- return true
- end
-
- false
+ return true if uid == current
end
- # Determine if the user is valid, and if so, return the UID
- def validuser?(value)
- info "Is '#{value}' a valid user?"
- return 0
- begin
- number = Integer(value)
- return number
- rescue ArgumentError
- number = nil
- end
- (number = uid(value)) && number
+ unless Puppet.features.root?
+ warnonce "Cannot manage ownership unless running as root"
+ return true
end
- def retrieve(resource)
- unless stat = resource.stat(false)
- return :absent
- end
-
- currentvalue = stat.uid
+ false
+ end
- # On OS X, files that are owned by -2 get returned as really
- # large UIDs instead of negative ones. This isn't a Ruby bug,
- # it's an OS X bug, since it shows up in perl, too.
- if currentvalue > Puppet[:maximum_uid].to_i
- self.warning "Apparently using negative UID (#{currentvalue}) on a platform that does not consistently handle them"
- currentvalue = :silly
- end
+ # Determine if the user is valid, and if so, return the UID
+ def validuser?(value)
+ info "Is '#{value}' a valid user?"
+ return 0
+ begin
+ number = Integer(value)
+ return number
+ rescue ArgumentError
+ number = nil
+ end
+ (number = uid(value)) && number
+ end
- currentvalue
+ def retrieve(resource)
+ unless stat = resource.stat(false)
+ return :absent
end
- def sync(path, links, should)
- info("should set '%s'%%owner to '%s'" % [path, should])
+ currentvalue = stat.uid
+
+ # On OS X, files that are owned by -2 get returned as really
+ # large UIDs instead of negative ones. This isn't a Ruby bug,
+ # it's an OS X bug, since it shows up in perl, too.
+ if currentvalue > Puppet[:maximum_uid].to_i
+ self.warning "Apparently using negative UID (#{currentvalue}) on a platform that does not consistently handle them"
+ currentvalue = :silly
end
+
+ currentvalue
+ end
+
+ def sync(path, links, should)
+ info("should set '%s'%%owner to '%s'" % [path, should])
+ end
end
diff --git a/lib/puppet/provider/group/directoryservice.rb b/lib/puppet/provider/group/directoryservice.rb
index d02273476..97fee883d 100644
--- a/lib/puppet/provider/group/directoryservice.rb
+++ b/lib/puppet/provider/group/directoryservice.rb
@@ -15,12 +15,12 @@
require 'puppet/provider/nameservice/directoryservice'
Puppet::Type.type(:group).provide :directoryservice, :parent => Puppet::Provider::NameService::DirectoryService do
- desc "Group management using DirectoryService on OS X.
+ desc "Group management using DirectoryService on OS X.
- "
+ "
- commands :dscl => "/usr/bin/dscl"
- confine :operatingsystem => :darwin
- defaultfor :operatingsystem => :darwin
- has_feature :manages_members
+ commands :dscl => "/usr/bin/dscl"
+ confine :operatingsystem => :darwin
+ defaultfor :operatingsystem => :darwin
+ has_feature :manages_members
end
diff --git a/lib/puppet/provider/group/groupadd.rb b/lib/puppet/provider/group/groupadd.rb
index 496db3ceb..e661ddd7f 100644
--- a/lib/puppet/provider/group/groupadd.rb
+++ b/lib/puppet/provider/group/groupadd.rb
@@ -1,29 +1,29 @@
require 'puppet/provider/nameservice/objectadd'
Puppet::Type.type(:group).provide :groupadd, :parent => Puppet::Provider::NameService::ObjectAdd do
- desc "Group management via ``groupadd`` and its ilk.
+ desc "Group management via ``groupadd`` and its ilk.
- The default for most platforms
+ The default for most platforms
- "
+ "
- commands :add => "groupadd", :delete => "groupdel", :modify => "groupmod"
+ commands :add => "groupadd", :delete => "groupdel", :modify => "groupmod"
- verify :gid, "GID must be an integer" do |value|
- value.is_a? Integer
- end
+ verify :gid, "GID must be an integer" do |value|
+ value.is_a? Integer
+ end
- def addcmd
- cmd = [command(:add)]
- if gid = @resource.should(:gid)
- unless gid == :absent
- cmd << flag(:gid) << gid
- end
- end
- cmd << "-o" if @resource.allowdupe?
- cmd << @resource[:name]
-
- cmd
+ def addcmd
+ cmd = [command(:add)]
+ if gid = @resource.should(:gid)
+ unless gid == :absent
+ cmd << flag(:gid) << gid
+ end
end
+ cmd << "-o" if @resource.allowdupe?
+ cmd << @resource[:name]
+
+ cmd
+ end
end
diff --git a/lib/puppet/provider/group/ldap.rb b/lib/puppet/provider/group/ldap.rb
index d0eca0d50..2737feea6 100644
--- a/lib/puppet/provider/group/ldap.rb
+++ b/lib/puppet/provider/group/ldap.rb
@@ -1,47 +1,47 @@
require 'puppet/provider/ldap'
Puppet::Type.type(:group).provide :ldap, :parent => Puppet::Provider::Ldap do
- desc "Group management via ``ldap``.
-
- This provider requires that you have valid values for all of the
- ldap-related settings, including ``ldapbase``. You will also almost
- definitely need settings for ``ldapuser`` and ``ldappassword``, so that
- your clients can write to ldap.
-
- Note that this provider will automatically generate a GID for you if you do
- not specify one, but it is a potentially expensive operation, as it
- iterates across all existing groups to pick the appropriate next one.
-
- "
-
- confine :true => Puppet.features.ldap?, :false => (Puppet[:ldapuser] == "")
-
- # We're mapping 'members' here because we want to make it
- # easy for the ldap user provider to manage groups. This
- # way it can just use the 'update' method in the group manager,
- # whereas otherwise it would need to replicate that code.
- manages(:posixGroup).at("ou=Groups").and.maps :name => :cn, :gid => :gidNumber, :members => :memberUid
-
- # Find the next gid after the current largest gid.
- provider = self
- manager.generates(:gidNumber).with do
- largest = 500
- if existing = provider.manager.search
- existing.each do |hash|
- next unless value = hash[:gid]
- num = value[0].to_i
- largest = num if num > largest
- end
- end
- largest + 1
+ desc "Group management via ``ldap``.
+
+ This provider requires that you have valid values for all of the
+ ldap-related settings, including ``ldapbase``. You will also almost
+ definitely need settings for ``ldapuser`` and ``ldappassword``, so that
+ your clients can write to ldap.
+
+ Note that this provider will automatically generate a GID for you if you do
+ not specify one, but it is a potentially expensive operation, as it
+ iterates across all existing groups to pick the appropriate next one.
+
+ "
+
+ confine :true => Puppet.features.ldap?, :false => (Puppet[:ldapuser] == "")
+
+ # We're mapping 'members' here because we want to make it
+ # easy for the ldap user provider to manage groups. This
+ # way it can just use the 'update' method in the group manager,
+ # whereas otherwise it would need to replicate that code.
+ manages(:posixGroup).at("ou=Groups").and.maps :name => :cn, :gid => :gidNumber, :members => :memberUid
+
+ # Find the next gid after the current largest gid.
+ provider = self
+ manager.generates(:gidNumber).with do
+ largest = 500
+ if existing = provider.manager.search
+ existing.each do |hash|
+ next unless value = hash[:gid]
+ num = value[0].to_i
+ largest = num if num > largest
+ end
end
+ largest + 1
+ end
- # Convert a group name to an id.
- def self.name2id(group)
- return nil unless result = manager.search("cn=#{group}") and result.length > 0
+ # Convert a group name to an id.
+ def self.name2id(group)
+ return nil unless result = manager.search("cn=#{group}") and result.length > 0
- # Only use the first result.
- group = result[0]
- gid = group[:gid][0]
- end
+ # Only use the first result.
+ group = result[0]
+ gid = group[:gid][0]
+ end
end
diff --git a/lib/puppet/provider/group/pw.rb b/lib/puppet/provider/group/pw.rb
index 0f549f2ec..e3dd714ee 100644
--- a/lib/puppet/provider/group/pw.rb
+++ b/lib/puppet/provider/group/pw.rb
@@ -1,34 +1,34 @@
require 'puppet/provider/nameservice/pw'
Puppet::Type.type(:group).provide :pw, :parent => Puppet::Provider::NameService::PW do
- desc "Group management via ``pw``.
+ desc "Group management via ``pw``.
- Only works on FreeBSD.
+ Only works on FreeBSD.
- "
+ "
- commands :pw => "/usr/sbin/pw"
- defaultfor :operatingsystem => :freebsd
+ commands :pw => "/usr/sbin/pw"
+ defaultfor :operatingsystem => :freebsd
- verify :gid, "GID must be an integer" do |value|
- value.is_a? Integer
- end
+ verify :gid, "GID must be an integer" do |value|
+ value.is_a? Integer
+ end
- def addcmd
- cmd = [command(:pw), "groupadd", @resource[:name]]
- if gid = @resource.should(:gid)
- unless gid == :absent
- cmd << flag(:gid) << gid
- end
- end
-
- # Apparently, contrary to the man page, groupadd does
- # not accept -o.
- #if @parent[:allowdupe] == :true
- # cmd << "-o"
- #end
-
- cmd
+ def addcmd
+ cmd = [command(:pw), "groupadd", @resource[:name]]
+ if gid = @resource.should(:gid)
+ unless gid == :absent
+ cmd << flag(:gid) << gid
+ end
end
+
+ # Apparently, contrary to the man page, groupadd does
+ # not accept -o.
+ #if @parent[:allowdupe] == :true
+ # cmd << "-o"
+ #end
+
+ cmd
+ end
end
diff --git a/lib/puppet/provider/host/parsed.rb b/lib/puppet/provider/host/parsed.rb
index be2f735cd..4f15eff3f 100644
--- a/lib/puppet/provider/host/parsed.rb
+++ b/lib/puppet/provider/host/parsed.rb
@@ -4,70 +4,70 @@ hosts = nil
case Facter.value(:operatingsystem)
when "Solaris"; hosts = "/etc/inet/hosts"
else
- hosts = "/etc/hosts"
+ hosts = "/etc/hosts"
end
- Puppet::Type.type(:host).provide(
- :parsed,
- :parent => Puppet::Provider::ParsedFile,
- :default_target => hosts,
+ Puppet::Type.type(:host).provide(
+ :parsed,
+ :parent => Puppet::Provider::ParsedFile,
+ :default_target => hosts,
- :filetype => :flat
+ :filetype => :flat
) do
- confine :exists => hosts
+ confine :exists => hosts
- text_line :comment, :match => /^#/
- text_line :blank, :match => /^\s*$/
+ text_line :comment, :match => /^#/
+ text_line :blank, :match => /^\s*$/
- record_line :parsed, :fields => %w{ip name host_aliases},
- :optional => %w{host_aliases},
- :rts => true do |line|
- hash = {}
- if line.sub!(/^(\S+)\s+(\S+)\s*/, '')
- hash[:ip] = $1
- hash[:name] = $2
+ record_line :parsed, :fields => %w{ip name host_aliases},
+ :optional => %w{host_aliases},
+ :rts => true do |line|
+ hash = {}
+ if line.sub!(/^(\S+)\s+(\S+)\s*/, '')
+ hash[:ip] = $1
+ hash[:name] = $2
- if line.empty?
- hash[:host_aliases] = []
- else
- line.sub!(/\s*/, '')
- line.sub!(/^([^#]+)\s*/) do |value|
- aliases = $1
- unless aliases =~ /^\s*$/
- hash[:host_aliases] = aliases.split(/\s+/)
- end
+ if line.empty?
+ hash[:host_aliases] = []
+ else
+ line.sub!(/\s*/, '')
+ line.sub!(/^([^#]+)\s*/) do |value|
+ aliases = $1
+ unless aliases =~ /^\s*$/
+ hash[:host_aliases] = aliases.split(/\s+/)
+ end
- ""
- end
- end
- else
- raise Puppet::Error, "Could not match '#{line}'"
+ ""
end
-
- hash[:host_aliases] = [] if hash[:host_aliases] == ""
-
- return hash
+ end
+ else
+ raise Puppet::Error, "Could not match '#{line}'"
end
- # Convert the current object into a host-style string.
- def self.to_line(hash)
- return super unless hash[:record_type] == :parsed
- [:ip, :name].each do |n|
- raise ArgumentError, "#{n} is a required attribute for hosts" unless hash[n] and hash[n] != :absent
- end
+ hash[:host_aliases] = [] if hash[:host_aliases] == ""
- str = "#{hash[:ip]}\t#{hash[:name]}"
+ return hash
+ end
- if hash.include? :host_aliases and !hash[:host_aliases].empty?
- if hash[:host_aliases].is_a? Array
- str += "\t#{hash[:host_aliases].join("\t")}"
- else
- raise ArgumentError, "Host aliases must be specified as an array"
- end
- end
+ # Convert the current object into a host-style string.
+ def self.to_line(hash)
+ return super unless hash[:record_type] == :parsed
+ [:ip, :name].each do |n|
+ raise ArgumentError, "#{n} is a required attribute for hosts" unless hash[n] and hash[n] != :absent
+ end
+
+ str = "#{hash[:ip]}\t#{hash[:name]}"
- str
+ if hash.include? :host_aliases and !hash[:host_aliases].empty?
+ if hash[:host_aliases].is_a? Array
+ str += "\t#{hash[:host_aliases].join("\t")}"
+ else
+ raise ArgumentError, "Host aliases must be specified as an array"
+ end
end
+
+ str
+ end
end
diff --git a/lib/puppet/provider/ldap.rb b/lib/puppet/provider/ldap.rb
index cc5c67fd2..b7d6baa9e 100644
--- a/lib/puppet/provider/ldap.rb
+++ b/lib/puppet/provider/ldap.rb
@@ -2,132 +2,132 @@ require 'puppet/provider'
# The base class for LDAP providers.
class Puppet::Provider::Ldap < Puppet::Provider
- require 'puppet/util/ldap/manager'
-
- class << self
- attr_reader :manager
+ require 'puppet/util/ldap/manager'
+
+ class << self
+ attr_reader :manager
+ end
+
+ # Look up all instances at our location. Yay.
+ def self.instances
+ return [] unless list = manager.search
+
+ list.collect { |entry| new(entry) }
+ end
+
+ # Specify the ldap manager for this provider, which is
+ # used to figure out how we actually interact with ldap.
+ def self.manages(*args)
+ @manager = Puppet::Util::Ldap::Manager.new
+ @manager.manages(*args)
+
+ # Set up our getter/setter methods.
+ mk_resource_methods
+ @manager
+ end
+
+ # Query all of our resources from ldap.
+ def self.prefetch(resources)
+ resources.each do |name, resource|
+ if result = manager.find(name)
+ result[:ensure] = :present
+ resource.provider = new(result)
+ else
+ resource.provider = new(:ensure => :absent)
+ end
end
-
- # Look up all instances at our location. Yay.
- def self.instances
- return [] unless list = manager.search
-
- list.collect { |entry| new(entry) }
+ end
+
+ def manager
+ self.class.manager
+ end
+
+ def create
+ @property_hash[:ensure] = :present
+ self.class.resource_type.validproperties.each do |property|
+ if val = resource.should(property)
+ @property_hash[property] = val
+ end
end
-
- # Specify the ldap manager for this provider, which is
- # used to figure out how we actually interact with ldap.
- def self.manages(*args)
- @manager = Puppet::Util::Ldap::Manager.new
- @manager.manages(*args)
-
- # Set up our getter/setter methods.
- mk_resource_methods
- @manager
+ end
+
+ def delete
+ @property_hash[:ensure] = :absent
+ end
+
+ def exists?
+ @property_hash[:ensure] != :absent
+ end
+
+ # Apply our changes to ldap, yo.
+ def flush
+ # Just call the manager's update() method.
+ @property_hash.delete(:groups)
+ @ldap_properties.delete(:groups)
+ manager.update(name, ldap_properties, properties)
+ @property_hash.clear
+ @ldap_properties.clear
+ end
+
+ def initialize(*args)
+ raise(Puppet::DevError, "No LDAP Configuration defined for #{self.class}") unless self.class.manager
+ raise(Puppet::DevError, "Invalid LDAP Configuration defined for #{self.class}") unless self.class.manager.valid?
+ super
+
+ @property_hash = @property_hash.inject({}) do |result, ary|
+ param, values = ary
+
+ # Skip any attributes we don't manage.
+ next result unless self.class.resource_type.valid_parameter?(param)
+
+ paramclass = self.class.resource_type.attrclass(param)
+
+ unless values.is_a?(Array)
+ result[param] = values
+ next result
+ end
+
+ # Only use the first value if the attribute class doesn't manage
+ # arrays of values.
+ if paramclass.superclass == Puppet::Parameter or paramclass.array_matching == :first
+ result[param] = values[0]
+ else
+ result[param] = values
+ end
+ result
end
- # Query all of our resources from ldap.
- def self.prefetch(resources)
- resources.each do |name, resource|
- if result = manager.find(name)
- result[:ensure] = :present
- resource.provider = new(result)
- else
- resource.provider = new(:ensure => :absent)
- end
- end
+ # Make a duplicate, so that we have a copy for comparison
+ # at the end.
+ @ldap_properties = @property_hash.dup
+ end
+
+ # Return the current state of ldap.
+ def ldap_properties
+ @ldap_properties.dup
+ end
+
+ # Return (and look up if necessary) the desired state.
+ def properties
+ if @property_hash.empty?
+ @property_hash = query || {:ensure => :absent}
+ @property_hash[:ensure] = :absent if @property_hash.empty?
end
-
- def manager
- self.class.manager
+ @property_hash.dup
+ end
+
+ # Collect the current attributes from ldap. Returns
+ # the results, but also stores the attributes locally,
+ # so we have something to compare against when we update.
+ # LAK:NOTE This is normally not used, because we rely on prefetching.
+ def query
+ # Use the module function.
+ unless attributes = manager.find(name)
+ @ldap_properties = {}
+ return nil
end
- def create
- @property_hash[:ensure] = :present
- self.class.resource_type.validproperties.each do |property|
- if val = resource.should(property)
- @property_hash[property] = val
- end
- end
- end
-
- def delete
- @property_hash[:ensure] = :absent
- end
-
- def exists?
- @property_hash[:ensure] != :absent
- end
-
- # Apply our changes to ldap, yo.
- def flush
- # Just call the manager's update() method.
- @property_hash.delete(:groups)
- @ldap_properties.delete(:groups)
- manager.update(name, ldap_properties, properties)
- @property_hash.clear
- @ldap_properties.clear
- end
-
- def initialize(*args)
- raise(Puppet::DevError, "No LDAP Configuration defined for #{self.class}") unless self.class.manager
- raise(Puppet::DevError, "Invalid LDAP Configuration defined for #{self.class}") unless self.class.manager.valid?
- super
-
- @property_hash = @property_hash.inject({}) do |result, ary|
- param, values = ary
-
- # Skip any attributes we don't manage.
- next result unless self.class.resource_type.valid_parameter?(param)
-
- paramclass = self.class.resource_type.attrclass(param)
-
- unless values.is_a?(Array)
- result[param] = values
- next result
- end
-
- # Only use the first value if the attribute class doesn't manage
- # arrays of values.
- if paramclass.superclass == Puppet::Parameter or paramclass.array_matching == :first
- result[param] = values[0]
- else
- result[param] = values
- end
- result
- end
-
- # Make a duplicate, so that we have a copy for comparison
- # at the end.
- @ldap_properties = @property_hash.dup
- end
-
- # Return the current state of ldap.
- def ldap_properties
- @ldap_properties.dup
- end
-
- # Return (and look up if necessary) the desired state.
- def properties
- if @property_hash.empty?
- @property_hash = query || {:ensure => :absent}
- @property_hash[:ensure] = :absent if @property_hash.empty?
- end
- @property_hash.dup
- end
-
- # Collect the current attributes from ldap. Returns
- # the results, but also stores the attributes locally,
- # so we have something to compare against when we update.
- # LAK:NOTE This is normally not used, because we rely on prefetching.
- def query
- # Use the module function.
- unless attributes = manager.find(name)
- @ldap_properties = {}
- return nil
- end
-
- @ldap_properties = attributes
- @ldap_properties.dup
- end
+ @ldap_properties = attributes
+ @ldap_properties.dup
+ end
end
diff --git a/lib/puppet/provider/macauthorization/macauthorization.rb b/lib/puppet/provider/macauthorization/macauthorization.rb
index 4c55d7280..fdf9fd18c 100644
--- a/lib/puppet/provider/macauthorization/macauthorization.rb
+++ b/lib/puppet/provider/macauthorization/macauthorization.rb
@@ -5,309 +5,309 @@ require 'tempfile'
Puppet::Type.type(:macauthorization).provide :macauthorization, :parent => Puppet::Provider do
- desc "Manage Mac OS X authorization database rules and rights.
+ desc "Manage Mac OS X authorization database rules and rights.
- "
+ "
- commands :security => "/usr/bin/security"
- commands :sw_vers => "/usr/bin/sw_vers"
+ commands :security => "/usr/bin/security"
+ commands :sw_vers => "/usr/bin/sw_vers"
- confine :operatingsystem => :darwin
+ confine :operatingsystem => :darwin
- # This should be confined based on macosx_productversion once
- # http://projects.reductivelabs.com/issues/show/1796
- # is resolved.
- if FileTest.exists?("/usr/bin/sw_vers")
- product_version = sw_vers "-productVersion"
+ # This should be confined based on macosx_productversion once
+ # http://projects.reductivelabs.com/issues/show/1796
+ # is resolved.
+ if FileTest.exists?("/usr/bin/sw_vers")
+ product_version = sw_vers "-productVersion"
- confine :true => if /^10.5/.match(product_version) or /^10.6/.match(product_version)
- true
- end
+ confine :true => if /^10.5/.match(product_version) or /^10.6/.match(product_version)
+ true
end
+ end
- defaultfor :operatingsystem => :darwin
-
- AuthDB = "/etc/authorization"
-
- @rights = {}
- @rules = {}
- @parsed_auth_db = {}
- @comment = "" # Not implemented yet. Is there any real need to?
-
- # This map exists due to the use of hyphens and reserved words in
- # the authorization schema.
- PuppetToNativeAttributeMap = { :allow_root => "allow-root",
- :authenticate_user => "authenticate-user",
- :auth_class => "class",
- :k_of_n => "k-of-n",
- :session_owner => "session-owner", }
-
- class << self
- attr_accessor :parsed_auth_db
- attr_accessor :rights
- attr_accessor :rules
- attr_accessor :comments # Not implemented yet.
-
- def prefetch(resources)
- self.populate_rules_rights
- end
-
- def instances
- if self.parsed_auth_db == {}
- self.prefetch(nil)
- end
- self.parsed_auth_db.collect do |k,v|
- new(:name => k)
- end
- end
-
- def populate_rules_rights
- auth_plist = Plist::parse_xml(AuthDB)
- raise Puppet::Error.new("Cannot parse: #{AuthDB}") if not auth_plist
- self.rights = auth_plist["rights"].dup
- self.rules = auth_plist["rules"].dup
- self.parsed_auth_db = self.rights.dup
- self.parsed_auth_db.merge!(self.rules.dup)
- end
+ defaultfor :operatingsystem => :darwin
- end
+ AuthDB = "/etc/authorization"
- # standard required provider instance methods
+ @rights = {}
+ @rules = {}
+ @parsed_auth_db = {}
+ @comment = "" # Not implemented yet. Is there any real need to?
- def initialize(resource)
- if self.class.parsed_auth_db == {}
- self.class.prefetch(resource)
- end
- super
- end
+ # This map exists due to the use of hyphens and reserved words in
+ # the authorization schema.
+ PuppetToNativeAttributeMap = { :allow_root => "allow-root",
+ :authenticate_user => "authenticate-user",
+ :auth_class => "class",
+ :k_of_n => "k-of-n",
+ :session_owner => "session-owner", }
+ class << self
+ attr_accessor :parsed_auth_db
+ attr_accessor :rights
+ attr_accessor :rules
+ attr_accessor :comments # Not implemented yet.
- def create
- # we just fill the @property_hash in here and let the flush method
- # deal with it rather than repeating code.
- new_values = {}
- validprops = Puppet::Type.type(resource.class.name).validproperties
- validprops.each do |prop|
- next if prop == :ensure
- if value = resource.should(prop) and value != ""
- new_values[prop] = value
- end
- end
- @property_hash = new_values.dup
+ def prefetch(resources)
+ self.populate_rules_rights
end
- def destroy
- # We explicitly delete here rather than in the flush method.
- case resource[:auth_type]
- when :right
- destroy_right
- when :rule
- destroy_rule
- else
- raise Puppet::Error.new("Must specify auth_type when destroying.")
- end
+ def instances
+ if self.parsed_auth_db == {}
+ self.prefetch(nil)
+ end
+ self.parsed_auth_db.collect do |k,v|
+ new(:name => k)
+ end
end
- def exists?
- !!self.class.parsed_auth_db.has_key?(resource[:name])
+ def populate_rules_rights
+ auth_plist = Plist::parse_xml(AuthDB)
+ raise Puppet::Error.new("Cannot parse: #{AuthDB}") if not auth_plist
+ self.rights = auth_plist["rights"].dup
+ self.rules = auth_plist["rules"].dup
+ self.parsed_auth_db = self.rights.dup
+ self.parsed_auth_db.merge!(self.rules.dup)
end
+ end
- def flush
- # deletion happens in the destroy methods
- if resource[:ensure] != :absent
- case resource[:auth_type]
- when :right
- flush_right
- when :rule
- flush_rule
- else
- raise Puppet::Error.new("flush requested for unknown type.")
- end
- @property_hash.clear
- end
+ # standard required provider instance methods
+
+ def initialize(resource)
+ if self.class.parsed_auth_db == {}
+ self.class.prefetch(resource)
+ end
+ super
+ end
+
+
+ def create
+ # we just fill the @property_hash in here and let the flush method
+ # deal with it rather than repeating code.
+ new_values = {}
+ validprops = Puppet::Type.type(resource.class.name).validproperties
+ validprops.each do |prop|
+ next if prop == :ensure
+ if value = resource.should(prop) and value != ""
+ new_values[prop] = value
+ end
end
+ @property_hash = new_values.dup
+ end
+
+ def destroy
+ # We explicitly delete here rather than in the flush method.
+ case resource[:auth_type]
+ when :right
+ destroy_right
+ when :rule
+ destroy_rule
+ else
+ raise Puppet::Error.new("Must specify auth_type when destroying.")
+ end
+ end
+
+ def exists?
+ !!self.class.parsed_auth_db.has_key?(resource[:name])
+ end
+
+
+ def flush
+ # deletion happens in the destroy methods
+ if resource[:ensure] != :absent
+ case resource[:auth_type]
+ when :right
+ flush_right
+ when :rule
+ flush_rule
+ else
+ raise Puppet::Error.new("flush requested for unknown type.")
+ end
+ @property_hash.clear
+ end
+ end
- # utility methods below
+ # utility methods below
- def destroy_right
- security "authorizationdb", :remove, resource[:name]
- end
+ def destroy_right
+ security "authorizationdb", :remove, resource[:name]
+ end
- def destroy_rule
- authdb = Plist::parse_xml(AuthDB)
- authdb_rules = authdb["rules"].dup
- if authdb_rules[resource[:name]]
- begin
- authdb["rules"].delete(resource[:name])
- Plist::Emit.save_plist(authdb, AuthDB)
- rescue Errno::EACCES => e
- raise Puppet::Error.new("Error saving #{AuthDB}: #{e}")
- end
- end
+ def destroy_rule
+ authdb = Plist::parse_xml(AuthDB)
+ authdb_rules = authdb["rules"].dup
+ if authdb_rules[resource[:name]]
+ begin
+ authdb["rules"].delete(resource[:name])
+ Plist::Emit.save_plist(authdb, AuthDB)
+ rescue Errno::EACCES => e
+ raise Puppet::Error.new("Error saving #{AuthDB}: #{e}")
+ end
end
-
- def flush_right
- # first we re-read the right just to make sure we're in sync for
- # values that weren't specified in the manifest. As we're supplying
- # the whole plist when specifying the right it seems safest to be
- # paranoid given the low cost of quering the db once more.
- cmds = []
- cmds << :security << "authorizationdb" << "read" << resource[:name]
- output = execute(cmds, :combine => false)
- current_values = Plist::parse_xml(output)
- current_values ||= {}
- specified_values = convert_plist_to_native_attributes(@property_hash)
-
- # take the current values, merge the specified values to obtain a
- # complete description of the new values.
- new_values = current_values.merge(specified_values)
- set_right(resource[:name], new_values)
+ end
+
+ def flush_right
+ # first we re-read the right just to make sure we're in sync for
+ # values that weren't specified in the manifest. As we're supplying
+ # the whole plist when specifying the right it seems safest to be
+ # paranoid given the low cost of quering the db once more.
+ cmds = []
+ cmds << :security << "authorizationdb" << "read" << resource[:name]
+ output = execute(cmds, :combine => false)
+ current_values = Plist::parse_xml(output)
+ current_values ||= {}
+ specified_values = convert_plist_to_native_attributes(@property_hash)
+
+ # take the current values, merge the specified values to obtain a
+ # complete description of the new values.
+ new_values = current_values.merge(specified_values)
+ set_right(resource[:name], new_values)
+ end
+
+ def flush_rule
+ authdb = Plist::parse_xml(AuthDB)
+ authdb_rules = authdb["rules"].dup
+ current_values = {}
+ current_values = authdb_rules[resource[:name]] if authdb_rules[resource[:name]]
+ specified_values = convert_plist_to_native_attributes(@property_hash)
+ new_values = current_values.merge(specified_values)
+ set_rule(resource[:name], new_values)
+ end
+
+ def set_right(name, values)
+ # Both creates and modifies rights as it simply overwrites them.
+ # The security binary only allows for writes using stdin, so we
+ # dump the values to a tempfile.
+ values = convert_plist_to_native_attributes(values)
+ tmp = Tempfile.new('puppet_macauthorization')
+ begin
+ Plist::Emit.save_plist(values, tmp.path)
+ cmds = []
+ cmds << :security << "authorizationdb" << "write" << name
+
+ output = execute(
+ cmds, :combine => false,
+
+ :stdinfile => tmp.path.to_s)
+ rescue Errno::EACCES => e
+ raise Puppet::Error.new("Cannot save right to #{tmp.path}: #{e}")
+ ensure
+ tmp.close
+ tmp.unlink
end
-
- def flush_rule
- authdb = Plist::parse_xml(AuthDB)
- authdb_rules = authdb["rules"].dup
- current_values = {}
- current_values = authdb_rules[resource[:name]] if authdb_rules[resource[:name]]
- specified_values = convert_plist_to_native_attributes(@property_hash)
- new_values = current_values.merge(specified_values)
- set_rule(resource[:name], new_values)
+ end
+
+ def set_rule(name, values)
+ # Both creates and modifies rules as it overwrites the entry in the
+ # rules dictionary. Unfortunately the security binary doesn't
+ # support modifying rules at all so we have to twiddle the whole
+ # plist... :( See Apple Bug #6386000
+ values = convert_plist_to_native_attributes(values)
+ authdb = Plist::parse_xml(AuthDB)
+ authdb["rules"][name] = values
+
+ begin
+ Plist::Emit.save_plist(authdb, AuthDB)
+ rescue
+ raise Puppet::Error.new("Error writing to: #{AuthDB}")
end
-
- def set_right(name, values)
- # Both creates and modifies rights as it simply overwrites them.
- # The security binary only allows for writes using stdin, so we
- # dump the values to a tempfile.
- values = convert_plist_to_native_attributes(values)
- tmp = Tempfile.new('puppet_macauthorization')
- begin
- Plist::Emit.save_plist(values, tmp.path)
- cmds = []
- cmds << :security << "authorizationdb" << "write" << name
-
- output = execute(
- cmds, :combine => false,
-
- :stdinfile => tmp.path.to_s)
- rescue Errno::EACCES => e
- raise Puppet::Error.new("Cannot save right to #{tmp.path}: #{e}")
- ensure
- tmp.close
- tmp.unlink
- end
+ end
+
+ def convert_plist_to_native_attributes(propertylist)
+ # This mainly converts the keys from the puppet attributes to the
+ # 'native' ones, but also enforces that the keys are all Strings
+ # rather than Symbols so that any merges of the resultant Hash are
+ # sane. The exception is booleans, where we coerce to a proper bool
+ # if they come in as a symbol.
+ newplist = {}
+ propertylist.each_pair do |key, value|
+ next if key == :ensure # not part of the auth db schema.
+ next if key == :auth_type # not part of the auth db schema.
+ case value
+ when true, :true
+ value = true
+ when false, :false
+ value = false
+ end
+ new_key = key
+ if PuppetToNativeAttributeMap.has_key?(key)
+ new_key = PuppetToNativeAttributeMap[key].to_s
+ elsif not key.is_a?(String)
+ new_key = key.to_s
+ end
+ newplist[new_key] = value
end
+ newplist
+ end
- def set_rule(name, values)
- # Both creates and modifies rules as it overwrites the entry in the
- # rules dictionary. Unfortunately the security binary doesn't
- # support modifying rules at all so we have to twiddle the whole
- # plist... :( See Apple Bug #6386000
- values = convert_plist_to_native_attributes(values)
- authdb = Plist::parse_xml(AuthDB)
- authdb["rules"][name] = values
-
- begin
- Plist::Emit.save_plist(authdb, AuthDB)
- rescue
- raise Puppet::Error.new("Error writing to: #{AuthDB}")
- end
- end
+ def retrieve_value(resource_name, attribute)
+ # We set boolean values to symbols when retrieving values
+ raise Puppet::Error.new("Cannot find #{resource_name} in auth db") if not self.class.parsed_auth_db.has_key?(resource_name)
- def convert_plist_to_native_attributes(propertylist)
- # This mainly converts the keys from the puppet attributes to the
- # 'native' ones, but also enforces that the keys are all Strings
- # rather than Symbols so that any merges of the resultant Hash are
- # sane. The exception is booleans, where we coerce to a proper bool
- # if they come in as a symbol.
- newplist = {}
- propertylist.each_pair do |key, value|
- next if key == :ensure # not part of the auth db schema.
- next if key == :auth_type # not part of the auth db schema.
- case value
- when true, :true
- value = true
- when false, :false
- value = false
- end
- new_key = key
- if PuppetToNativeAttributeMap.has_key?(key)
- new_key = PuppetToNativeAttributeMap[key].to_s
- elsif not key.is_a?(String)
- new_key = key.to_s
- end
- newplist[new_key] = value
- end
- newplist
+ if PuppetToNativeAttributeMap.has_key?(attribute)
+ native_attribute = PuppetToNativeAttributeMap[attribute]
+ else
+ native_attribute = attribute.to_s
end
- def retrieve_value(resource_name, attribute)
- # We set boolean values to symbols when retrieving values
- raise Puppet::Error.new("Cannot find #{resource_name} in auth db") if not self.class.parsed_auth_db.has_key?(resource_name)
-
- if PuppetToNativeAttributeMap.has_key?(attribute)
- native_attribute = PuppetToNativeAttributeMap[attribute]
- else
- native_attribute = attribute.to_s
- end
-
- if self.class.parsed_auth_db[resource_name].has_key?(native_attribute)
- value = self.class.parsed_auth_db[resource_name][native_attribute]
- case value
- when true, :true
- value = :true
- when false, :false
- value = :false
- end
-
- @property_hash[attribute] = value
- return value
- else
- @property_hash.delete(attribute)
- return "" # so ralsh doesn't display it.
- end
+ if self.class.parsed_auth_db[resource_name].has_key?(native_attribute)
+ value = self.class.parsed_auth_db[resource_name][native_attribute]
+ case value
+ when true, :true
+ value = :true
+ when false, :false
+ value = :false
+ end
+
+ @property_hash[attribute] = value
+ return value
+ else
+ @property_hash.delete(attribute)
+ return "" # so ralsh doesn't display it.
end
+ end
- # property methods below
- #
- # We define them all dynamically apart from auth_type which is a special
- # case due to not being in the actual authorization db schema.
+ # property methods below
+ #
+ # We define them all dynamically apart from auth_type which is a special
+ # case due to not being in the actual authorization db schema.
- properties = [ :allow_root, :authenticate_user, :auth_class, :comment,
- :group, :k_of_n, :mechanisms, :rule, :session_owner,
- :shared, :timeout, :tries ]
+ properties = [ :allow_root, :authenticate_user, :auth_class, :comment,
+ :group, :k_of_n, :mechanisms, :rule, :session_owner,
+ :shared, :timeout, :tries ]
- properties.each do |field|
- define_method(field.to_s) do
- retrieve_value(resource[:name], field)
- end
-
- define_method(field.to_s + "=") do |value|
- @property_hash[field] = value
- end
+ properties.each do |field|
+ define_method(field.to_s) do
+ retrieve_value(resource[:name], field)
end
- def auth_type
- if resource.should(:auth_type) != nil
- return resource.should(:auth_type)
- elsif self.exists?
- # this is here just for ralsh, so it can work out what type it is.
- if self.class.rights.has_key?(resource[:name])
- return :right
- elsif self.class.rules.has_key?(resource[:name])
- return :rule
- else
- raise Puppet::Error.new("#{resource[:name]} is unknown type.")
- end
- else
- raise Puppet::Error.new("auth_type required for new resources.")
- end
+ define_method(field.to_s + "=") do |value|
+ @property_hash[field] = value
end
-
- def auth_type=(value)
- @property_hash[:auth_type] = value
+ end
+
+ def auth_type
+ if resource.should(:auth_type) != nil
+ return resource.should(:auth_type)
+ elsif self.exists?
+ # this is here just for ralsh, so it can work out what type it is.
+ if self.class.rights.has_key?(resource[:name])
+ return :right
+ elsif self.class.rules.has_key?(resource[:name])
+ return :rule
+ else
+ raise Puppet::Error.new("#{resource[:name]} is unknown type.")
+ end
+ else
+ raise Puppet::Error.new("auth_type required for new resources.")
end
+ end
+
+ def auth_type=(value)
+ @property_hash[:auth_type] = value
+ end
end
diff --git a/lib/puppet/provider/mailalias/aliases.rb b/lib/puppet/provider/mailalias/aliases.rb
index 388fd631c..35c2f98fe 100755
--- a/lib/puppet/provider/mailalias/aliases.rb
+++ b/lib/puppet/provider/mailalias/aliases.rb
@@ -1,44 +1,44 @@
require 'puppet/provider/parsedfile'
- Puppet::Type.type(:mailalias).provide(
- :aliases,
- :parent => Puppet::Provider::ParsedFile,
- :default_target => "/etc/aliases",
+ Puppet::Type.type(:mailalias).provide(
+ :aliases,
+ :parent => Puppet::Provider::ParsedFile,
+ :default_target => "/etc/aliases",
- :filetype => :flat
+ :filetype => :flat
) do
- text_line :comment, :match => /^#/
- text_line :blank, :match => /^\s*$/
+ text_line :comment, :match => /^#/
+ text_line :blank, :match => /^\s*$/
- record_line :aliases, :fields => %w{name recipient}, :separator => /\s*:\s*/, :block_eval => :instance do
- def post_parse(record)
- # LAK:NOTE See http://snurl.com/21zf8 [groups_google_com]
- # It's not sufficient to assign to an existing hash.
- recipient = record[:recipient].split(/\s*,\s*/).collect { |d| d.gsub(/^['"]|['"]$/, '') }
- record[:recipient] = recipient
- record
- end
+ record_line :aliases, :fields => %w{name recipient}, :separator => /\s*:\s*/, :block_eval => :instance do
+ def post_parse(record)
+ # LAK:NOTE See http://snurl.com/21zf8 [groups_google_com]
+ # It's not sufficient to assign to an existing hash.
+ recipient = record[:recipient].split(/\s*,\s*/).collect { |d| d.gsub(/^['"]|['"]$/, '') }
+ record[:recipient] = recipient
+ record
+ end
- def process(line)
- ret = {}
- records = line.split(':',2)
- ret[:name] = records[0].strip
- ret[:recipient] = records[1].strip
- ret
- end
+ def process(line)
+ ret = {}
+ records = line.split(':',2)
+ ret[:name] = records[0].strip
+ ret[:recipient] = records[1].strip
+ ret
+ end
- def to_line(record)
- dest = record[:recipient].collect do |d|
- # Quote aliases that have non-alpha chars
- if d =~ /[^-\w@.]/
- '"%s"' % d
- else
- d
- end
- end.join(",")
- "#{record[:name]}: #{dest}"
+ def to_line(record)
+ dest = record[:recipient].collect do |d|
+ # Quote aliases that have non-alpha chars
+ if d =~ /[^-\w@.]/
+ '"%s"' % d
+ else
+ d
end
+ end.join(",")
+ "#{record[:name]}: #{dest}"
end
+ end
end
diff --git a/lib/puppet/provider/maillist/mailman.rb b/lib/puppet/provider/maillist/mailman.rb
index cfb788b31..4fdc20a69 100755
--- a/lib/puppet/provider/maillist/mailman.rb
+++ b/lib/puppet/provider/maillist/mailman.rb
@@ -1,110 +1,110 @@
require 'puppet/provider/parsedfile'
Puppet::Type.type(:maillist).provide(:mailman) do
- if [ "CentOS", "RedHat", "Fedora" ].any? { |os| Facter.value(:operatingsystem) == os }
- commands :list_lists => "/usr/lib/mailman/bin/list_lists", :rmlist => "/usr/lib/mailman/bin/rmlist", :newlist => "/usr/lib/mailman/bin/newlist"
- commands :mailman => "/usr/lib/mailman/mail/mailman"
- else
- # This probably won't work for non-Debian installs, but this path is sure not to be in the PATH.
- commands :list_lists => "list_lists", :rmlist => "rmlist", :newlist => "newlist"
- commands :mailman => "/var/lib/mailman/mail/mailman"
- end
+ if [ "CentOS", "RedHat", "Fedora" ].any? { |os| Facter.value(:operatingsystem) == os }
+ commands :list_lists => "/usr/lib/mailman/bin/list_lists", :rmlist => "/usr/lib/mailman/bin/rmlist", :newlist => "/usr/lib/mailman/bin/newlist"
+ commands :mailman => "/usr/lib/mailman/mail/mailman"
+ else
+ # This probably won't work for non-Debian installs, but this path is sure not to be in the PATH.
+ commands :list_lists => "list_lists", :rmlist => "rmlist", :newlist => "newlist"
+ commands :mailman => "/var/lib/mailman/mail/mailman"
+ end
- mk_resource_methods
+ mk_resource_methods
- # Return a list of existing mailman instances.
- def self.instances
- list_lists.split("\n").reject { |line| line.include?("matching mailing lists") }.collect do |line|
- name, description = line.sub(/^\s+/, '').sub(/\s+$/, '').split(/\s+-\s+/)
- description = :absent if description.include?("no description available")
- new(:ensure => :present, :name => name, :description => description)
- end
+ # Return a list of existing mailman instances.
+ def self.instances
+ list_lists.split("\n").reject { |line| line.include?("matching mailing lists") }.collect do |line|
+ name, description = line.sub(/^\s+/, '').sub(/\s+$/, '').split(/\s+-\s+/)
+ description = :absent if description.include?("no description available")
+ new(:ensure => :present, :name => name, :description => description)
end
+ end
- # Prefetch our list list, yo.
- def self.prefetch(lists)
- instances.each do |prov|
- if list = lists[prov.name] || lists[prov.name.downcase]
- list.provider = prov
- end
- end
+ # Prefetch our list list, yo.
+ def self.prefetch(lists)
+ instances.each do |prov|
+ if list = lists[prov.name] || lists[prov.name.downcase]
+ list.provider = prov
+ end
end
+ end
- def aliases
- mailman = self.class.command(:mailman)
- name = self.name.downcase
- aliases = {name => "| #{mailman} post #{name}"}
- %w{admin bounces confirm join leave owner request subscribe unsubscribe}.each do |address|
- aliases["#{name}-#{address}"] = "| #{mailman} #{address} #{name}"
- end
- aliases
+ def aliases
+ mailman = self.class.command(:mailman)
+ name = self.name.downcase
+ aliases = {name => "| #{mailman} post #{name}"}
+ %w{admin bounces confirm join leave owner request subscribe unsubscribe}.each do |address|
+ aliases["#{name}-#{address}"] = "| #{mailman} #{address} #{name}"
end
+ aliases
+ end
- # Create the list.
- def create
- args = []
- if val = @resource[:mailserver]
- args << "--emailhost" << val
- end
- if val = @resource[:webserver]
- args << "--urlhost" << val
- end
-
- args << self.name
- if val = @resource[:admin]
- args << val
- else
- raise ArgumentError, "Mailman lists require an administrator email address"
- end
- if val = @resource[:password]
- args << val
- else
- raise ArgumentError, "Mailman lists require an administrator password"
- end
- newlist(*args)
+ # Create the list.
+ def create
+ args = []
+ if val = @resource[:mailserver]
+ args << "--emailhost" << val
end
-
- # Delete the list.
- def destroy(purge = false)
- args = []
- args << "--archives" if purge
- args << self.name
- rmlist(*args)
+ if val = @resource[:webserver]
+ args << "--urlhost" << val
end
- # Does our list exist already?
- def exists?
- properties[:ensure] != :absent
+ args << self.name
+ if val = @resource[:admin]
+ args << val
+ else
+ raise ArgumentError, "Mailman lists require an administrator email address"
end
-
- # Clear out the cached values.
- def flush
- @property_hash.clear
+ if val = @resource[:password]
+ args << val
+ else
+ raise ArgumentError, "Mailman lists require an administrator password"
end
+ newlist(*args)
+ end
- # Look up the current status.
- def properties
- if @property_hash.empty?
- @property_hash = query || {:ensure => :absent}
- @property_hash[:ensure] = :absent if @property_hash.empty?
- end
- @property_hash.dup
- end
+ # Delete the list.
+ def destroy(purge = false)
+ args = []
+ args << "--archives" if purge
+ args << self.name
+ rmlist(*args)
+ end
+
+ # Does our list exist already?
+ def exists?
+ properties[:ensure] != :absent
+ end
- # Remove the list and its archives.
- def purge
- destroy(true)
+ # Clear out the cached values.
+ def flush
+ @property_hash.clear
+ end
+
+ # Look up the current status.
+ def properties
+ if @property_hash.empty?
+ @property_hash = query || {:ensure => :absent}
+ @property_hash[:ensure] = :absent if @property_hash.empty?
end
+ @property_hash.dup
+ end
+
+ # Remove the list and its archives.
+ def purge
+ destroy(true)
+ end
- # Pull the current state of the list from the full list. We're
- # getting some double entendre here....
- def query
- self.class.instances.each do |list|
- if list.name == self.name or list.name.downcase == self.name
- return list.properties
- end
- end
- nil
+ # Pull the current state of the list from the full list. We're
+ # getting some double entendre here....
+ def query
+ self.class.instances.each do |list|
+ if list.name == self.name or list.name.downcase == self.name
+ return list.properties
+ end
end
+ nil
+ end
end
diff --git a/lib/puppet/provider/mcx/mcxcontent.rb b/lib/puppet/provider/mcx/mcxcontent.rb
index ba9ca31dd..cb5adc698 100644
--- a/lib/puppet/provider/mcx/mcxcontent.rb
+++ b/lib/puppet/provider/mcx/mcxcontent.rb
@@ -21,185 +21,185 @@ require 'tempfile'
Puppet::Type.type(:mcx).provide :mcxcontent, :parent => Puppet::Provider do
- desc "MCX Settings management using DirectoryService on OS X.
+ desc "MCX Settings management using DirectoryService on OS X.
- This provider manages the entire MCXSettings attribute available
- to some directory services nodes. This management is 'all or nothing'
- in that discrete application domain key value pairs are not managed
- by this provider.
+ This provider manages the entire MCXSettings attribute available
+ to some directory services nodes. This management is 'all or nothing'
+ in that discrete application domain key value pairs are not managed
+ by this provider.
- It is recommended to use WorkGroup Manager to configure Users, Groups,
- Computers, or ComputerLists, then use 'ralsh mcx' to generate a puppet
- manifest from the resulting configuration.
+ It is recommended to use WorkGroup Manager to configure Users, Groups,
+ Computers, or ComputerLists, then use 'ralsh mcx' to generate a puppet
+ manifest from the resulting configuration.
- Original Author: Jeff McCune (mccune.jeff@gmail.com)
+ Original Author: Jeff McCune (mccune.jeff@gmail.com)
"
- # This provides a mapping of puppet types to DirectoryService
- # type strings.
- TypeMap = {
- :user => "Users",
- :group => "Groups",
- :computer => "Computers",
- :computerlist => "ComputerLists",
- }
-
- class MCXContentProviderException < Exception
-
- end
-
- commands :dscl => "/usr/bin/dscl"
- confine :operatingsystem => :darwin
- defaultfor :operatingsystem => :darwin
-
- # self.instances is all important.
- # This is the only class method, it returns
- # an array of instances of this class.
- def self.instances
- mcx_list = []
- for ds_type in TypeMap.keys
- ds_path = "/Local/Default/#{TypeMap[ds_type]}"
- output = dscl 'localhost', '-list', ds_path
- member_list = output.split
- for ds_name in member_list
- content = mcxexport(ds_type, ds_name)
- if content.empty?
- Puppet.debug "/#{TypeMap[ds_type]}/#{ds_name} has no MCX data."
- else
- # This node has MCX data.
-
- rsrc = self.new(
- :name => "/#{TypeMap[ds_type]}/#{ds_name}",
- :ds_type => ds_type,
- :ds_name => ds_name,
-
- :content => content)
- mcx_list << rsrc
- end
- end
+ # This provides a mapping of puppet types to DirectoryService
+ # type strings.
+ TypeMap = {
+ :user => "Users",
+ :group => "Groups",
+ :computer => "Computers",
+ :computerlist => "ComputerLists",
+ }
+
+ class MCXContentProviderException < Exception
+
+ end
+
+ commands :dscl => "/usr/bin/dscl"
+ confine :operatingsystem => :darwin
+ defaultfor :operatingsystem => :darwin
+
+ # self.instances is all important.
+ # This is the only class method, it returns
+ # an array of instances of this class.
+ def self.instances
+ mcx_list = []
+ for ds_type in TypeMap.keys
+ ds_path = "/Local/Default/#{TypeMap[ds_type]}"
+ output = dscl 'localhost', '-list', ds_path
+ member_list = output.split
+ for ds_name in member_list
+ content = mcxexport(ds_type, ds_name)
+ if content.empty?
+ Puppet.debug "/#{TypeMap[ds_type]}/#{ds_name} has no MCX data."
+ else
+ # This node has MCX data.
+
+ rsrc = self.new(
+ :name => "/#{TypeMap[ds_type]}/#{ds_name}",
+ :ds_type => ds_type,
+ :ds_name => ds_name,
+
+ :content => content)
+ mcx_list << rsrc
end
- mcx_list
+ end
end
-
- private
-
- # mcxexport is used by instances, and therefore
- # a class method.
- def self.mcxexport(ds_type, ds_name)
- ds_t = TypeMap[ds_type]
- ds_n = ds_name.to_s
- ds_path = "/Local/Default/#{ds_t}/#{ds_n}"
- dscl 'localhost', '-mcxexport', ds_path
+ mcx_list
+ end
+
+ private
+
+ # mcxexport is used by instances, and therefore
+ # a class method.
+ def self.mcxexport(ds_type, ds_name)
+ ds_t = TypeMap[ds_type]
+ ds_n = ds_name.to_s
+ ds_path = "/Local/Default/#{ds_t}/#{ds_n}"
+ dscl 'localhost', '-mcxexport', ds_path
+ end
+
+ def mcximport(ds_type, ds_name, val)
+ ds_t = TypeMap[ds_type]
+ ds_n = ds_name.to_s
+ ds_path = "/Local/Default/#{ds_t}/#{ds_name}"
+
+ tmp = Tempfile.new('puppet_mcx')
+ begin
+ tmp << val
+ tmp.flush
+ dscl 'localhost', '-mcximport', ds_path, tmp.path
+ ensure
+ tmp.close
+ tmp.unlink
end
-
- def mcximport(ds_type, ds_name, val)
- ds_t = TypeMap[ds_type]
- ds_n = ds_name.to_s
- ds_path = "/Local/Default/#{ds_t}/#{ds_name}"
-
- tmp = Tempfile.new('puppet_mcx')
- begin
- tmp << val
- tmp.flush
- dscl 'localhost', '-mcximport', ds_path, tmp.path
- ensure
- tmp.close
- tmp.unlink
- end
+ end
+
+ # Given the resource name string, parse ds_type out.
+ def parse_type(name)
+ tmp = name.split('/')[1]
+ if ! tmp.is_a? String
+ raise MCXContentProviderException,
+ "Coult not parse ds_type from resource name '#{name}'. Specify with ds_type parameter."
end
-
- # Given the resource name string, parse ds_type out.
- def parse_type(name)
- tmp = name.split('/')[1]
- if ! tmp.is_a? String
- raise MCXContentProviderException,
- "Coult not parse ds_type from resource name '#{name}'. Specify with ds_type parameter."
- end
- # De-pluralize and downcase.
- tmp = tmp.chop.downcase.to_sym
- if not TypeMap.keys.member? tmp
- raise MCXContentProviderException,
- "Coult not parse ds_type from resource name '#{name}'. Specify with ds_type parameter."
- end
- tmp
+ # De-pluralize and downcase.
+ tmp = tmp.chop.downcase.to_sym
+ if not TypeMap.keys.member? tmp
+ raise MCXContentProviderException,
+ "Coult not parse ds_type from resource name '#{name}'. Specify with ds_type parameter."
end
-
- # Given the resource name string, parse ds_name out.
- def parse_name(name)
- ds_name = name.split('/')[2]
- if ! ds_name.is_a? String
- raise MCXContentProviderException,
- "Could not parse ds_name from resource name '#{name}'. Specify with ds_name parameter."
- end
- ds_name
+ tmp
+ end
+
+ # Given the resource name string, parse ds_name out.
+ def parse_name(name)
+ ds_name = name.split('/')[2]
+ if ! ds_name.is_a? String
+ raise MCXContentProviderException,
+ "Could not parse ds_name from resource name '#{name}'. Specify with ds_name parameter."
end
+ ds_name
+ end
+
+ # Gather ds_type and ds_name from resource or
+ # parse it out of the name.
+ # This is a private instance method, not a class method.
+ def get_dsparams
+ ds_type = resource[:ds_type]
+ ds_type ||= parse_type(resource[:name])
+ raise MCXContentProviderException unless TypeMap.keys.include? ds_type.to_sym
+
+ ds_name = resource[:ds_name]
+ ds_name ||= parse_name(resource[:name])
+
+ rval = {
+ :ds_type => ds_type.to_sym,
+ :ds_name => ds_name,
+ }
- # Gather ds_type and ds_name from resource or
- # parse it out of the name.
- # This is a private instance method, not a class method.
- def get_dsparams
- ds_type = resource[:ds_type]
- ds_type ||= parse_type(resource[:name])
- raise MCXContentProviderException unless TypeMap.keys.include? ds_type.to_sym
-
- ds_name = resource[:ds_name]
- ds_name ||= parse_name(resource[:name])
-
- rval = {
- :ds_type => ds_type.to_sym,
- :ds_name => ds_name,
- }
-
- return rval
+ return rval
- end
+ end
- public
+ public
- def create
- self.content=(resource[:content])
- end
+ def create
+ self.content=(resource[:content])
+ end
- def destroy
- ds_parms = get_dsparams
- ds_t = TypeMap[ds_parms[:ds_type]]
- ds_n = ds_parms[:ds_name].to_s
- ds_path = "/Local/Default/#{ds_t}/#{ds_n}"
+ def destroy
+ ds_parms = get_dsparams
+ ds_t = TypeMap[ds_parms[:ds_type]]
+ ds_n = ds_parms[:ds_name].to_s
+ ds_path = "/Local/Default/#{ds_t}/#{ds_n}"
- dscl 'localhost', '-mcxdelete', ds_path
- end
+ dscl 'localhost', '-mcxdelete', ds_path
+ end
- def exists?
- # JJM Just re-use the content method and see if it's empty.
- begin
- mcx = content
- rescue Puppet::ExecutionFailure => e
- return false
- end
- has_mcx = ! mcx.empty?
+ def exists?
+ # JJM Just re-use the content method and see if it's empty.
+ begin
+ mcx = content
+ rescue Puppet::ExecutionFailure => e
+ return false
end
+ has_mcx = ! mcx.empty?
+ end
- def content
- ds_parms = get_dsparams
+ def content
+ ds_parms = get_dsparams
- mcx = self.class.mcxexport(
- ds_parms[:ds_type],
+ mcx = self.class.mcxexport(
+ ds_parms[:ds_type],
- ds_parms[:ds_name])
- mcx
- end
+ ds_parms[:ds_name])
+ mcx
+ end
- def content=(value)
- # dscl localhost -mcximport
- ds_parms = get_dsparams
+ def content=(value)
+ # dscl localhost -mcximport
+ ds_parms = get_dsparams
- mcx = mcximport(
- ds_parms[:ds_type],
- ds_parms[:ds_name],
+ mcx = mcximport(
+ ds_parms[:ds_type],
+ ds_parms[:ds_name],
- resource[:content])
- mcx
- end
+ resource[:content])
+ mcx
+ end
end
diff --git a/lib/puppet/provider/mount.rb b/lib/puppet/provider/mount.rb
index 2136339a3..393ae56c9 100644
--- a/lib/puppet/provider/mount.rb
+++ b/lib/puppet/provider/mount.rb
@@ -6,46 +6,46 @@ require 'puppet'
# A module just to store the mount/unmount methods. Individual providers
# still need to add the mount commands manually.
module Puppet::Provider::Mount
- # This only works when the mount point is synced to the fstab.
- def mount
- # Manually pass the mount options in, since some OSes *cough*OS X*cough* don't
- # read from /etc/fstab but still want to use this type.
- args = []
- args << "-o" << self.options if self.options and self.options != :absent
- args << resource[:name]
+ # This only works when the mount point is synced to the fstab.
+ def mount
+ # Manually pass the mount options in, since some OSes *cough*OS X*cough* don't
+ # read from /etc/fstab but still want to use this type.
+ args = []
+ args << "-o" << self.options if self.options and self.options != :absent
+ args << resource[:name]
- flush if respond_to?(:flush)
- mountcmd(*args)
- end
+ flush if respond_to?(:flush)
+ mountcmd(*args)
+ end
- def remount
- info "Remounting"
- if resource[:remounts] == :true
- mountcmd "-o", "remount", resource[:name]
- else
- unmount
- mount
- end
+ def remount
+ info "Remounting"
+ if resource[:remounts] == :true
+ mountcmd "-o", "remount", resource[:name]
+ else
+ unmount
+ mount
end
+ end
- # This only works when the mount point is synced to the fstab.
- def unmount
- umount resource[:name]
- end
+ # This only works when the mount point is synced to the fstab.
+ def unmount
+ umount resource[:name]
+ end
- # Is the mount currently mounted?
- def mounted?
- platform = Facter.value("operatingsystem")
- name = resource[:name]
- mounts = mountcmd.split("\n").find do |line|
- case platform
- when "Darwin"
- line =~ / on #{name} / or line =~ %r{ on /private/var/automount#{name}}
- when "Solaris"
- line =~ /^#{name} on /
- else
- line =~ / on #{name} /
- end
- end
+ # Is the mount currently mounted?
+ def mounted?
+ platform = Facter.value("operatingsystem")
+ name = resource[:name]
+ mounts = mountcmd.split("\n").find do |line|
+ case platform
+ when "Darwin"
+ line =~ / on #{name} / or line =~ %r{ on /private/var/automount#{name}}
+ when "Solaris"
+ line =~ /^#{name} on /
+ else
+ line =~ / on #{name} /
+ end
end
+ end
end
diff --git a/lib/puppet/provider/mount/parsed.rb b/lib/puppet/provider/mount/parsed.rb
index 1100ad62c..82d1628bd 100755
--- a/lib/puppet/provider/mount/parsed.rb
+++ b/lib/puppet/provider/mount/parsed.rb
@@ -5,43 +5,43 @@ fstab = nil
case Facter.value(:operatingsystem)
when "Solaris"; fstab = "/etc/vfstab"
else
- fstab = "/etc/fstab"
+ fstab = "/etc/fstab"
end
- Puppet::Type.type(:mount).provide(
- :parsed,
- :parent => Puppet::Provider::ParsedFile,
- :default_target => fstab,
+ Puppet::Type.type(:mount).provide(
+ :parsed,
+ :parent => Puppet::Provider::ParsedFile,
+ :default_target => fstab,
- :filetype => :flat
+ :filetype => :flat
) do
- include Puppet::Provider::Mount
- #confine :exists => fstab
+ include Puppet::Provider::Mount
+ #confine :exists => fstab
- commands :mountcmd => "mount", :umount => "umount"
+ commands :mountcmd => "mount", :umount => "umount"
- @platform = Facter["operatingsystem"].value
- case @platform
- when "Solaris"
- @fields = [:device, :blockdevice, :name, :fstype, :pass, :atboot, :options]
- else
- @fields = [:device, :name, :fstype, :options, :dump, :pass]
- @fielddefaults = [ nil ] * 4 + [ "0", "2" ]
- end
+ @platform = Facter["operatingsystem"].value
+ case @platform
+ when "Solaris"
+ @fields = [:device, :blockdevice, :name, :fstype, :pass, :atboot, :options]
+ else
+ @fields = [:device, :name, :fstype, :options, :dump, :pass]
+ @fielddefaults = [ nil ] * 4 + [ "0", "2" ]
+ end
- text_line :comment, :match => /^\s*#/
- text_line :blank, :match => /^\s*$/
+ text_line :comment, :match => /^\s*#/
+ text_line :blank, :match => /^\s*$/
- optional_fields = @fields - [:device, :name, :blockdevice]
- mandatory_fields = @fields - optional_fields
+ optional_fields = @fields - [:device, :name, :blockdevice]
+ mandatory_fields = @fields - optional_fields
- # fstab will ignore lines that have fewer than the mandatory number of columns,
- # so we should, too.
- field_pattern = '(\s*(?>\S+))'
- text_line :incomplete, :match => /^(?!#{field_pattern}{#{mandatory_fields.length}})/
+ # fstab will ignore lines that have fewer than the mandatory number of columns,
+ # so we should, too.
+ field_pattern = '(\s*(?>\S+))'
+ text_line :incomplete, :match => /^(?!#{field_pattern}{#{mandatory_fields.length}})/
- record_line self.name, :fields => @fields, :separator => /\s+/, :joiner => "\t", :optional => optional_fields
+ record_line self.name, :fields => @fields, :separator => /\s+/, :joiner => "\t", :optional => optional_fields
end
diff --git a/lib/puppet/provider/naginator.rb b/lib/puppet/provider/naginator.rb
index 1006a4c0d..5c610fb31 100644
--- a/lib/puppet/provider/naginator.rb
+++ b/lib/puppet/provider/naginator.rb
@@ -7,52 +7,52 @@ require 'puppet/external/nagios'
# The base class for all Naginator providers.
class Puppet::Provider::Naginator < Puppet::Provider::ParsedFile
- NAME_STRING = "## --PUPPET_NAME-- (called '_naginator_name' in the manifest)"
- # Retrieve the associated class from Nagios::Base.
- def self.nagios_type
- unless @nagios_type
- name = resource_type.name.to_s.sub(/^nagios_/, '')
- unless @nagios_type = Nagios::Base.type(name.to_sym)
- raise Puppet::DevError, "Could not find nagios type '#{name}'"
- end
-
- # And add our 'ensure' settings, since they aren't a part of
- # Naginator by default
- @nagios_type.send(:attr_accessor, :ensure, :target, :on_disk)
- end
- @nagios_type
+ NAME_STRING = "## --PUPPET_NAME-- (called '_naginator_name' in the manifest)"
+ # Retrieve the associated class from Nagios::Base.
+ def self.nagios_type
+ unless @nagios_type
+ name = resource_type.name.to_s.sub(/^nagios_/, '')
+ unless @nagios_type = Nagios::Base.type(name.to_sym)
+ raise Puppet::DevError, "Could not find nagios type '#{name}'"
+ end
+
+ # And add our 'ensure' settings, since they aren't a part of
+ # Naginator by default
+ @nagios_type.send(:attr_accessor, :ensure, :target, :on_disk)
end
-
- def self.parse(text)
- Nagios::Parser.new.parse(text.gsub(NAME_STRING, "_naginator_name"))
- rescue => detail
- raise Puppet::Error, "Could not parse configuration for #{resource_type.name}: #{detail}"
- end
-
- def self.to_file(records)
- header + records.collect { |record| record.to_s }.join("\n").gsub("_naginator_name", NAME_STRING)
- end
-
- def self.skip_record?(record)
- false
- end
-
- def self.valid_attr?(klass, attr_name)
- nagios_type.parameters.include?(attr_name)
- end
-
- def initialize(resource = nil)
- if resource.is_a?(Nagios::Base)
- # 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 if resource
- # LAK 2007-05-09: Keep the model stuff around for backward compatibility
- @model = resource
- @property_hash = self.class.nagios_type.new
- else
- @property_hash = self.class.nagios_type.new
- end
+ @nagios_type
+ end
+
+ def self.parse(text)
+ Nagios::Parser.new.parse(text.gsub(NAME_STRING, "_naginator_name"))
+ rescue => detail
+ raise Puppet::Error, "Could not parse configuration for #{resource_type.name}: #{detail}"
+ end
+
+ def self.to_file(records)
+ header + records.collect { |record| record.to_s }.join("\n").gsub("_naginator_name", NAME_STRING)
+ end
+
+ def self.skip_record?(record)
+ false
+ end
+
+ def self.valid_attr?(klass, attr_name)
+ nagios_type.parameters.include?(attr_name)
+ end
+
+ def initialize(resource = nil)
+ if resource.is_a?(Nagios::Base)
+ # 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 if resource
+ # LAK 2007-05-09: Keep the model stuff around for backward compatibility
+ @model = resource
+ @property_hash = self.class.nagios_type.new
+ else
+ @property_hash = self.class.nagios_type.new
end
+ end
end
diff --git a/lib/puppet/provider/nameservice.rb b/lib/puppet/provider/nameservice.rb
index 6564a4154..7339b646e 100644
--- a/lib/puppet/provider/nameservice.rb
+++ b/lib/puppet/provider/nameservice.rb
@@ -4,270 +4,270 @@ require 'puppet'
# their backend, but they're pretty similar on the front-end. This class
# provides a way for them all to be as similar as possible.
class Puppet::Provider::NameService < Puppet::Provider
- class << self
- def autogen_default(param)
- defined?(@autogen_defaults) ? @autogen_defaults[symbolize(param)] : nil
- end
-
- def autogen_defaults(hash)
- @autogen_defaults ||= {}
- hash.each do |param, value|
- @autogen_defaults[symbolize(param)] = value
- end
- end
+ class << self
+ def autogen_default(param)
+ defined?(@autogen_defaults) ? @autogen_defaults[symbolize(param)] : nil
+ end
- def initvars
- @checks = {}
- super
- end
+ def autogen_defaults(hash)
+ @autogen_defaults ||= {}
+ hash.each do |param, value|
+ @autogen_defaults[symbolize(param)] = value
+ end
+ end
- def instances
- objects = []
- listbyname do |name|
- objects << new(:name => name, :ensure => :present)
- end
+ def initvars
+ @checks = {}
+ super
+ end
- objects
- end
+ def instances
+ objects = []
+ listbyname do |name|
+ objects << new(:name => name, :ensure => :present)
+ end
- def option(name, option)
- name = name.intern if name.is_a? String
- (defined?(@options) and @options.include? name and @options[name].include? option) ? @options[name][option] : nil
- end
+ objects
+ end
- def options(name, hash)
- raise Puppet::DevError, "#{name} is not a valid attribute for #{resource_type.name}" unless resource_type.valid_parameter?(name)
- @options ||= {}
- @options[name] ||= {}
+ def option(name, option)
+ name = name.intern if name.is_a? String
+ (defined?(@options) and @options.include? name and @options[name].include? option) ? @options[name][option] : nil
+ end
- # Set options individually, so we can call the options method
- # multiple times.
- hash.each do |param, value|
- @options[name][param] = value
- end
- end
+ def options(name, hash)
+ raise Puppet::DevError, "#{name} is not a valid attribute for #{resource_type.name}" unless resource_type.valid_parameter?(name)
+ @options ||= {}
+ @options[name] ||= {}
- # List everything out by name. Abstracted a bit so that it works
- # for both users and groups.
- def listbyname
- names = []
- Etc.send("set#{section()}ent")
- begin
- while ent = Etc.send("get#{section()}ent")
- names << ent.name
- yield ent.name if block_given?
- end
- ensure
- Etc.send("end#{section()}ent")
- end
-
- names
- end
+ # Set options individually, so we can call the options method
+ # multiple times.
+ hash.each do |param, value|
+ @options[name][param] = value
+ end
+ end
- def resource_type=(resource_type)
- super
- @resource_type.validproperties.each do |prop|
- next if prop == :ensure
- define_method(prop) { get(prop) || :absent} unless public_method_defined?(prop)
- define_method(prop.to_s + "=") { |*vals| set(prop, *vals) } unless public_method_defined?(prop.to_s + "=")
- end
+ # List everything out by name. Abstracted a bit so that it works
+ # for both users and groups.
+ def listbyname
+ names = []
+ Etc.send("set#{section()}ent")
+ begin
+ while ent = Etc.send("get#{section()}ent")
+ names << ent.name
+ yield ent.name if block_given?
end
+ ensure
+ Etc.send("end#{section()}ent")
+ end
- # This is annoying, but there really aren't that many options,
- # and this *is* built into Ruby.
- def section
- unless defined?(@resource_type)
- raise Puppet::DevError,
- "Cannot determine Etc section without a resource type"
-
- end
-
- if @resource_type.name == :group
- "gr"
- else
- "pw"
- end
- end
+ names
+ end
- def validate(name, value)
- name = name.intern if name.is_a? String
- if @checks.include? name
- block = @checks[name][:block]
- raise ArgumentError, "Invalid value #{value}: #{@checks[name][:error]}" unless block.call(value)
- end
- end
+ def resource_type=(resource_type)
+ super
+ @resource_type.validproperties.each do |prop|
+ next if prop == :ensure
+ define_method(prop) { get(prop) || :absent} unless public_method_defined?(prop)
+ define_method(prop.to_s + "=") { |*vals| set(prop, *vals) } unless public_method_defined?(prop.to_s + "=")
+ end
+ end
- def verify(name, error, &block)
- name = name.intern if name.is_a? String
- @checks[name] = {:error => error, :block => block}
- end
+ # This is annoying, but there really aren't that many options,
+ # and this *is* built into Ruby.
+ def section
+ unless defined?(@resource_type)
+ raise Puppet::DevError,
+ "Cannot determine Etc section without a resource type"
- private
+ end
- def op(property)
- @ops[property.name] || ("-#{property.name}")
- end
+ if @resource_type.name == :group
+ "gr"
+ else
+ "pw"
+ end
end
- # Autogenerate a value. Mostly used for uid/gid, but also used heavily
- # with DirectoryServices, because DirectoryServices is stupid.
- def autogen(field)
- field = symbolize(field)
- id_generators = {:user => :uid, :group => :gid}
- if id_generators[@resource.class.name] == field
- return autogen_id(field)
- else
- if value = self.class.autogen_default(field)
- return value
- elsif respond_to?("autogen_#{field}")
- return send("autogen_#{field}")
- else
- return nil
- end
- end
+ def validate(name, value)
+ name = name.intern if name.is_a? String
+ if @checks.include? name
+ block = @checks[name][:block]
+ raise ArgumentError, "Invalid value #{value}: #{@checks[name][:error]}" unless block.call(value)
+ end
end
- # Autogenerate either a uid or a gid. This is hard-coded: we can only
- # generate one field type per class.
- def autogen_id(field)
- highest = 0
-
- group = method = nil
- case @resource.class.name
- when :user; group = :passwd; method = :uid
- when :group; group = :group; method = :gid
- else
- raise Puppet::DevError, "Invalid resource name #{resource}"
- end
+ def verify(name, error, &block)
+ name = name.intern if name.is_a? String
+ @checks[name] = {:error => error, :block => block}
+ end
- # Make sure we don't use the same value multiple times
- if defined?(@@prevauto)
- @@prevauto += 1
- else
- Etc.send(group) { |obj|
- if obj.gid > highest
- highest = obj.send(method) unless obj.send(method) > 65000
- end
- }
-
- @@prevauto = highest + 1
- end
+ private
- @@prevauto
+ def op(property)
+ @ops[property.name] || ("-#{property.name}")
+ end
+ end
+
+ # Autogenerate a value. Mostly used for uid/gid, but also used heavily
+ # with DirectoryServices, because DirectoryServices is stupid.
+ def autogen(field)
+ field = symbolize(field)
+ id_generators = {:user => :uid, :group => :gid}
+ if id_generators[@resource.class.name] == field
+ return autogen_id(field)
+ else
+ if value = self.class.autogen_default(field)
+ return value
+ elsif respond_to?("autogen_#{field}")
+ return send("autogen_#{field}")
+ else
+ return nil
+ end
+ end
+ end
+
+ # Autogenerate either a uid or a gid. This is hard-coded: we can only
+ # generate one field type per class.
+ def autogen_id(field)
+ highest = 0
+
+ group = method = nil
+ case @resource.class.name
+ when :user; group = :passwd; method = :uid
+ when :group; group = :group; method = :gid
+ else
+ raise Puppet::DevError, "Invalid resource name #{resource}"
end
- def create
- if exists?
- info "already exists"
- # The object already exists
- return nil
+ # Make sure we don't use the same value multiple times
+ if defined?(@@prevauto)
+ @@prevauto += 1
+ else
+ Etc.send(group) { |obj|
+ if obj.gid > highest
+ highest = obj.send(method) unless obj.send(method) > 65000
end
+ }
- begin
- execute(self.addcmd)
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not create #{@resource.class.name} #{@resource.name}: #{detail}"
- end
+ @@prevauto = highest + 1
end
- def delete
- unless exists?
- info "already absent"
- # the object already doesn't exist
- return nil
- end
+ @@prevauto
+ end
- begin
- execute(self.deletecmd)
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not delete #{@resource.class.name} #{@resource.name}: #{detail}"
- end
+ def create
+ if exists?
+ info "already exists"
+ # The object already exists
+ return nil
end
- def ensure
- if exists?
- :present
- else
- :absent
- end
+ begin
+ execute(self.addcmd)
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error, "Could not create #{@resource.class.name} #{@resource.name}: #{detail}"
end
+ end
- # Does our object exist?
- def exists?
- !!getinfo(true)
+ def delete
+ unless exists?
+ info "already absent"
+ # the object already doesn't exist
+ return nil
end
- # Retrieve a specific value by name.
- def get(param)
- (hash = getinfo(false)) ? hash[param] : nil
+ begin
+ execute(self.deletecmd)
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error, "Could not delete #{@resource.class.name} #{@resource.name}: #{detail}"
end
+ end
- # Retrieve what we can about our object
- def getinfo(refresh)
- if @objectinfo.nil? or refresh == true
- @etcmethod ||= ("get" + self.class.section.to_s + "nam").intern
- begin
- @objectinfo = Etc.send(@etcmethod, @resource[:name])
- rescue ArgumentError => detail
- @objectinfo = nil
- end
- end
-
- # Now convert our Etc struct into a hash.
- @objectinfo ? info2hash(@objectinfo) : nil
+ def ensure
+ if exists?
+ :present
+ else
+ :absent
+ end
+ end
+
+ # Does our object exist?
+ def exists?
+ !!getinfo(true)
+ end
+
+ # Retrieve a specific value by name.
+ def get(param)
+ (hash = getinfo(false)) ? hash[param] : nil
+ end
+
+ # Retrieve what we can about our object
+ def getinfo(refresh)
+ if @objectinfo.nil? or refresh == true
+ @etcmethod ||= ("get" + self.class.section.to_s + "nam").intern
+ begin
+ @objectinfo = Etc.send(@etcmethod, @resource[:name])
+ rescue ArgumentError => detail
+ @objectinfo = nil
+ end
end
- # The list of all groups the user is a member of. Different
- # user mgmt systems will need to override this method.
- def groups
- groups = []
-
- # Reset our group list
- Etc.setgrent
+ # Now convert our Etc struct into a hash.
+ @objectinfo ? info2hash(@objectinfo) : nil
+ end
- user = @resource[:name]
+ # The list of all groups the user is a member of. Different
+ # user mgmt systems will need to override this method.
+ def groups
+ groups = []
- # Now iterate across all of the groups, adding each one our
- # user is a member of
- while group = Etc.getgrent
- members = group.mem
+ # Reset our group list
+ Etc.setgrent
- groups << group.name if members.include? user
- end
+ user = @resource[:name]
- # We have to close the file, so each listing is a separate
- # reading of the file.
- Etc.endgrent
+ # Now iterate across all of the groups, adding each one our
+ # user is a member of
+ while group = Etc.getgrent
+ members = group.mem
- groups.join(",")
+ groups << group.name if members.include? user
end
- # Convert the Etc struct into a hash.
- def info2hash(info)
- hash = {}
- self.class.resource_type.validproperties.each do |param|
- method = posixmethod(param)
- hash[param] = info.send(posixmethod(param)) if info.respond_to? method
- end
+ # We have to close the file, so each listing is a separate
+ # reading of the file.
+ Etc.endgrent
- hash
+ groups.join(",")
+ end
+
+ # Convert the Etc struct into a hash.
+ def info2hash(info)
+ hash = {}
+ self.class.resource_type.validproperties.each do |param|
+ method = posixmethod(param)
+ hash[param] = info.send(posixmethod(param)) if info.respond_to? method
end
- def initialize(resource)
- super
+ hash
+ end
- @objectinfo = nil
- end
+ def initialize(resource)
+ super
- def set(param, value)
- self.class.validate(param, value)
- cmd = modifycmd(param, value)
- raise Puppet::DevError, "Nameservice command must be an array" unless cmd.is_a?(Array)
- begin
- execute(cmd)
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not set #{param} on #{@resource.class.name}[#{@resource.name}]: #{detail}"
- end
+ @objectinfo = nil
+ end
+
+ def set(param, value)
+ self.class.validate(param, value)
+ cmd = modifycmd(param, value)
+ raise Puppet::DevError, "Nameservice command must be an array" unless cmd.is_a?(Array)
+ begin
+ execute(cmd)
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error, "Could not set #{param} on #{@resource.class.name}[#{@resource.name}]: #{detail}"
end
+ end
end
diff --git a/lib/puppet/provider/nameservice/directoryservice.rb b/lib/puppet/provider/nameservice/directoryservice.rb
index 060ed4c31..76fc466ac 100644
--- a/lib/puppet/provider/nameservice/directoryservice.rb
+++ b/lib/puppet/provider/nameservice/directoryservice.rb
@@ -20,497 +20,497 @@ require 'cgi'
class Puppet::Provider::NameService
class DirectoryService < Puppet::Provider::NameService
- # JJM: Dive into the singleton_class
- class << self
- # JJM: This allows us to pass information when calling
- # Puppet::Type.type
- # e.g. Puppet::Type.type(:user).provide :directoryservice, :ds_path => "Users"
- # This is referenced in the get_ds_path class method
- attr_writer :ds_path
- attr_writer :macosx_version_major
+ # JJM: Dive into the singleton_class
+ class << self
+ # JJM: This allows us to pass information when calling
+ # Puppet::Type.type
+ # e.g. Puppet::Type.type(:user).provide :directoryservice, :ds_path => "Users"
+ # This is referenced in the get_ds_path class method
+ attr_writer :ds_path
+ attr_writer :macosx_version_major
+ end
+
+ initvars
+
+ commands :dscl => "/usr/bin/dscl"
+ commands :dseditgroup => "/usr/sbin/dseditgroup"
+ commands :sw_vers => "/usr/bin/sw_vers"
+ confine :operatingsystem => :darwin
+ defaultfor :operatingsystem => :darwin
+
+
+ # JJM 2007-07-25: This map is used to map NameService attributes to their
+ # corresponding DirectoryService attribute names.
+ # See: http://images.apple.com/server/docs/Open_Directory_v10.4.pdf
+ # JJM: Note, this is de-coupled from the Puppet::Type, and must
+ # be actively maintained. There may also be collisions with different
+ # types (Users, Groups, Mounts, Hosts, etc...)
+ @@ds_to_ns_attribute_map = {
+ 'RecordName' => :name,
+ 'PrimaryGroupID' => :gid,
+ 'NFSHomeDirectory' => :home,
+ 'UserShell' => :shell,
+ 'UniqueID' => :uid,
+ 'RealName' => :comment,
+ 'Password' => :password,
+ 'GeneratedUID' => :guid,
+ 'IPAddress' => :ip_address,
+ 'ENetAddress' => :en_address,
+ 'GroupMembership' => :members,
+ }
+ # JJM The same table as above, inverted.
+ @@ns_to_ds_attribute_map = {
+ :name => 'RecordName',
+ :gid => 'PrimaryGroupID',
+ :home => 'NFSHomeDirectory',
+ :shell => 'UserShell',
+ :uid => 'UniqueID',
+ :comment => 'RealName',
+ :password => 'Password',
+ :guid => 'GeneratedUID',
+ :en_address => 'ENetAddress',
+ :ip_address => 'IPAddress',
+ :members => 'GroupMembership',
+ }
+
+ @@password_hash_dir = "/var/db/shadow/hash"
+
+ def self.instances
+ # JJM Class method that provides an array of instance objects of this
+ # type.
+ # JJM: Properties are dependent on the Puppet::Type we're managine.
+ type_property_array = [:name] + @resource_type.validproperties
+
+ # Create a new instance of this Puppet::Type for each object present
+ # on the system.
+ list_all_present.collect do |name_string|
+ self.new(single_report(name_string, *type_property_array))
end
-
- initvars
-
- commands :dscl => "/usr/bin/dscl"
- commands :dseditgroup => "/usr/sbin/dseditgroup"
- commands :sw_vers => "/usr/bin/sw_vers"
- confine :operatingsystem => :darwin
- defaultfor :operatingsystem => :darwin
-
-
- # JJM 2007-07-25: This map is used to map NameService attributes to their
- # corresponding DirectoryService attribute names.
- # See: http://images.apple.com/server/docs/Open_Directory_v10.4.pdf
- # JJM: Note, this is de-coupled from the Puppet::Type, and must
- # be actively maintained. There may also be collisions with different
- # types (Users, Groups, Mounts, Hosts, etc...)
- @@ds_to_ns_attribute_map = {
- 'RecordName' => :name,
- 'PrimaryGroupID' => :gid,
- 'NFSHomeDirectory' => :home,
- 'UserShell' => :shell,
- 'UniqueID' => :uid,
- 'RealName' => :comment,
- 'Password' => :password,
- 'GeneratedUID' => :guid,
- 'IPAddress' => :ip_address,
- 'ENetAddress' => :en_address,
- 'GroupMembership' => :members,
- }
- # JJM The same table as above, inverted.
- @@ns_to_ds_attribute_map = {
- :name => 'RecordName',
- :gid => 'PrimaryGroupID',
- :home => 'NFSHomeDirectory',
- :shell => 'UserShell',
- :uid => 'UniqueID',
- :comment => 'RealName',
- :password => 'Password',
- :guid => 'GeneratedUID',
- :en_address => 'ENetAddress',
- :ip_address => 'IPAddress',
- :members => 'GroupMembership',
- }
-
- @@password_hash_dir = "/var/db/shadow/hash"
-
- def self.instances
- # JJM Class method that provides an array of instance objects of this
- # type.
- # JJM: Properties are dependent on the Puppet::Type we're managine.
- type_property_array = [:name] + @resource_type.validproperties
-
- # Create a new instance of this Puppet::Type for each object present
- # on the system.
- list_all_present.collect do |name_string|
- self.new(single_report(name_string, *type_property_array))
- end
+ end
+
+ def self.get_ds_path
+ # JJM: 2007-07-24 This method dynamically returns the DS path we're concerned with.
+ # For example, if we're working with an user type, this will be /Users
+ # with a group type, this will be /Groups.
+ # @ds_path is an attribute of the class itself.
+ return @ds_path if defined?(@ds_path)
+ # JJM: "Users" or "Groups" etc ... (Based on the Puppet::Type)
+ # Remember this is a class method, so self.class is Class
+ # Also, @resource_type seems to be the reference to the
+ # Puppet::Type this class object is providing for.
+ @resource_type.name.to_s.capitalize + "s"
+ end
+
+ def self.get_macosx_version_major
+ return @macosx_version_major if defined?(@macosx_version_major)
+ begin
+ # Make sure we've loaded all of the facts
+ Facter.loadfacts
+
+ if Facter.value(:macosx_productversion_major)
+ product_version_major = Facter.value(:macosx_productversion_major)
+ else
+ # TODO: remove this code chunk once we require Facter 1.5.5 or higher.
+ Puppet.warning("DEPRECATION WARNING: Future versions of the directoryservice provider will require Facter 1.5.5 or newer.")
+ product_version = Facter.value(:macosx_productversion)
+ fail("Could not determine OS X version from Facter") if product_version.nil?
+ product_version_major = product_version.scan(/(\d+)\.(\d+)./).join(".")
+ end
+ fail("#{product_version_major} is not supported by the directoryservice provider") if %w{10.0 10.1 10.2 10.3}.include?(product_version_major)
+ @macosx_version_major = product_version_major
+ return @macosx_version_major
+ rescue Puppet::ExecutionFailure => detail
+ fail("Could not determine OS X version: #{detail}")
end
+ end
- def self.get_ds_path
- # JJM: 2007-07-24 This method dynamically returns the DS path we're concerned with.
- # For example, if we're working with an user type, this will be /Users
- # with a group type, this will be /Groups.
- # @ds_path is an attribute of the class itself.
- return @ds_path if defined?(@ds_path)
- # JJM: "Users" or "Groups" etc ... (Based on the Puppet::Type)
- # Remember this is a class method, so self.class is Class
- # Also, @resource_type seems to be the reference to the
- # Puppet::Type this class object is providing for.
- @resource_type.name.to_s.capitalize + "s"
- end
- def self.get_macosx_version_major
- return @macosx_version_major if defined?(@macosx_version_major)
- begin
- # Make sure we've loaded all of the facts
- Facter.loadfacts
-
- if Facter.value(:macosx_productversion_major)
- product_version_major = Facter.value(:macosx_productversion_major)
- else
- # TODO: remove this code chunk once we require Facter 1.5.5 or higher.
- Puppet.warning("DEPRECATION WARNING: Future versions of the directoryservice provider will require Facter 1.5.5 or newer.")
- product_version = Facter.value(:macosx_productversion)
- fail("Could not determine OS X version from Facter") if product_version.nil?
- product_version_major = product_version.scan(/(\d+)\.(\d+)./).join(".")
- end
- fail("#{product_version_major} is not supported by the directoryservice provider") if %w{10.0 10.1 10.2 10.3}.include?(product_version_major)
- @macosx_version_major = product_version_major
- return @macosx_version_major
- rescue Puppet::ExecutionFailure => detail
- fail("Could not determine OS X version: #{detail}")
- end
+ def self.list_all_present
+ # JJM: List all objects of this Puppet::Type already present on the system.
+ begin
+ dscl_output = execute(get_exec_preamble("-list"))
+ rescue Puppet::ExecutionFailure => detail
+ fail("Could not get #{@resource_type.name} list from DirectoryService")
end
-
-
- def self.list_all_present
- # JJM: List all objects of this Puppet::Type already present on the system.
- begin
- dscl_output = execute(get_exec_preamble("-list"))
- rescue Puppet::ExecutionFailure => detail
- fail("Could not get #{@resource_type.name} list from DirectoryService")
- end
- dscl_output.split("\n")
+ dscl_output.split("\n")
+ end
+
+ def self.parse_dscl_url_data(dscl_output)
+ # we need to construct a Hash from the dscl -url output to match
+ # that returned by the dscl -plist output for 10.5+ clients.
+ #
+ # Nasty assumptions:
+ # a) no values *end* in a colon ':', only keys
+ # b) if a line ends in a colon and the next line does start with
+ # a space, then the second line is a value of the first.
+ # c) (implied by (b)) keys don't start with spaces.
+
+ dscl_plist = {}
+ dscl_output.split("\n").inject([]) do |array, line|
+ if line =~ /^\s+/ # it's a value
+ array[-1] << line # add the value to the previous key
+ else
+ array << line
+ end
+ array
+ end.compact
+
+ dscl_output.each do |line|
+ # This should be a 'normal' entry. key and value on one line.
+ # We split on ': ' to deal with keys/values with a colon in them.
+ split_array = line.split(/:\s+/)
+ key = split_array.first
+ value = CGI::unescape(split_array.last.strip.chomp)
+ # We need to treat GroupMembership separately as it is currently
+ # the only attribute we care about multiple values for, and
+ # the values can never contain spaces (shortnames)
+ # We also make every value an array to be consistent with the
+ # output of dscl -plist under 10.5
+ if key == "GroupMembership"
+ dscl_plist[key] = value.split(/\s/)
+ else
+ dscl_plist[key] = [value]
+ end
end
-
- def self.parse_dscl_url_data(dscl_output)
- # we need to construct a Hash from the dscl -url output to match
- # that returned by the dscl -plist output for 10.5+ clients.
- #
- # Nasty assumptions:
- # a) no values *end* in a colon ':', only keys
- # b) if a line ends in a colon and the next line does start with
- # a space, then the second line is a value of the first.
- # c) (implied by (b)) keys don't start with spaces.
-
- dscl_plist = {}
- dscl_output.split("\n").inject([]) do |array, line|
- if line =~ /^\s+/ # it's a value
- array[-1] << line # add the value to the previous key
- else
- array << line
- end
- array
- end.compact
-
- dscl_output.each do |line|
- # This should be a 'normal' entry. key and value on one line.
- # We split on ': ' to deal with keys/values with a colon in them.
- split_array = line.split(/:\s+/)
- key = split_array.first
- value = CGI::unescape(split_array.last.strip.chomp)
- # We need to treat GroupMembership separately as it is currently
- # the only attribute we care about multiple values for, and
- # the values can never contain spaces (shortnames)
- # We also make every value an array to be consistent with the
- # output of dscl -plist under 10.5
- if key == "GroupMembership"
- dscl_plist[key] = value.split(/\s/)
- else
- dscl_plist[key] = [value]
- end
- end
- dscl_plist
+ dscl_plist
+ end
+
+ def self.parse_dscl_plist_data(dscl_output)
+ Plist.parse_xml(dscl_output)
+ end
+
+ def self.generate_attribute_hash(input_hash, *type_properties)
+ attribute_hash = {}
+ input_hash.keys.each do |key|
+ ds_attribute = key.sub("dsAttrTypeStandard:", "")
+ next unless (@@ds_to_ns_attribute_map.keys.include?(ds_attribute) and type_properties.include? @@ds_to_ns_attribute_map[ds_attribute])
+ ds_value = input_hash[key]
+ case @@ds_to_ns_attribute_map[ds_attribute]
+ when :members
+ ds_value = ds_value # only members uses arrays so far
+ when :gid, :uid
+ # OS X stores objects like uid/gid as strings.
+ # Try casting to an integer for these cases to be
+ # consistent with the other providers and the group type
+ # validation
+ begin
+ ds_value = Integer(ds_value[0])
+ rescue ArgumentError
+ ds_value = ds_value[0]
+ end
+ else ds_value = ds_value[0]
+ end
+ attribute_hash[@@ds_to_ns_attribute_map[ds_attribute]] = ds_value
end
- def self.parse_dscl_plist_data(dscl_output)
- Plist.parse_xml(dscl_output)
+ # NBK: need to read the existing password here as it's not actually
+ # stored in the user record. It is stored at a path that involves the
+ # UUID of the user record for non-Mobile local acccounts.
+ # Mobile Accounts are out of scope for this provider for now
+ attribute_hash[:password] = self.get_password(attribute_hash[:guid]) if @resource_type.validproperties.include?(:password) and Puppet.features.root?
+ attribute_hash
+ end
+
+ def self.single_report(resource_name, *type_properties)
+ # JJM 2007-07-24:
+ # Given a the name of an object and a list of properties of that
+ # object, return all property values in a hash.
+ #
+ # This class method returns nil if the object doesn't exist
+ # Otherwise, it returns a hash of the object properties.
+
+ all_present_str_array = list_all_present
+
+ # NBK: shortcut the process if the resource is missing
+ return nil unless all_present_str_array.include? resource_name
+
+ dscl_vector = get_exec_preamble("-read", resource_name)
+ begin
+ dscl_output = execute(dscl_vector)
+ rescue Puppet::ExecutionFailure => detail
+ fail("Could not get report. command execution failed.")
end
- def self.generate_attribute_hash(input_hash, *type_properties)
- attribute_hash = {}
- input_hash.keys.each do |key|
- ds_attribute = key.sub("dsAttrTypeStandard:", "")
- next unless (@@ds_to_ns_attribute_map.keys.include?(ds_attribute) and type_properties.include? @@ds_to_ns_attribute_map[ds_attribute])
- ds_value = input_hash[key]
- case @@ds_to_ns_attribute_map[ds_attribute]
- when :members
- ds_value = ds_value # only members uses arrays so far
- when :gid, :uid
- # OS X stores objects like uid/gid as strings.
- # Try casting to an integer for these cases to be
- # consistent with the other providers and the group type
- # validation
- begin
- ds_value = Integer(ds_value[0])
- rescue ArgumentError
- ds_value = ds_value[0]
- end
- else ds_value = ds_value[0]
- end
- attribute_hash[@@ds_to_ns_attribute_map[ds_attribute]] = ds_value
- end
-
- # NBK: need to read the existing password here as it's not actually
- # stored in the user record. It is stored at a path that involves the
- # UUID of the user record for non-Mobile local acccounts.
- # Mobile Accounts are out of scope for this provider for now
- attribute_hash[:password] = self.get_password(attribute_hash[:guid]) if @resource_type.validproperties.include?(:password) and Puppet.features.root?
- attribute_hash
+ # Two code paths is ugly, but until we can drop 10.4 support we don't
+ # have a lot of choice. Ultimately this should all be done using Ruby
+ # to access the DirectoryService APIs directly, but that's simply not
+ # feasible for a while yet.
+ case self.get_macosx_version_major
+ when "10.4"
+ dscl_plist = self.parse_dscl_url_data(dscl_output)
+ when "10.5", "10.6"
+ dscl_plist = self.parse_dscl_plist_data(dscl_output)
end
- def self.single_report(resource_name, *type_properties)
- # JJM 2007-07-24:
- # Given a the name of an object and a list of properties of that
- # object, return all property values in a hash.
- #
- # This class method returns nil if the object doesn't exist
- # Otherwise, it returns a hash of the object properties.
-
- all_present_str_array = list_all_present
-
- # NBK: shortcut the process if the resource is missing
- return nil unless all_present_str_array.include? resource_name
-
- dscl_vector = get_exec_preamble("-read", resource_name)
- begin
- dscl_output = execute(dscl_vector)
- rescue Puppet::ExecutionFailure => detail
- fail("Could not get report. command execution failed.")
- end
-
- # Two code paths is ugly, but until we can drop 10.4 support we don't
- # have a lot of choice. Ultimately this should all be done using Ruby
- # to access the DirectoryService APIs directly, but that's simply not
- # feasible for a while yet.
- case self.get_macosx_version_major
- when "10.4"
- dscl_plist = self.parse_dscl_url_data(dscl_output)
- when "10.5", "10.6"
- dscl_plist = self.parse_dscl_plist_data(dscl_output)
- end
-
- self.generate_attribute_hash(dscl_plist, *type_properties)
+ self.generate_attribute_hash(dscl_plist, *type_properties)
+ end
+
+ def self.get_exec_preamble(ds_action, resource_name = nil)
+ # JJM 2007-07-24
+ # DSCL commands are often repetitive and contain the same positional
+ # arguments over and over. See http://developer.apple.com/documentation/Porting/Conceptual/PortingUnix/additionalfeatures/chapter_10_section_9.html
+ # for an example of what I mean.
+ # This method spits out proper DSCL commands for us.
+ # We EXPECT name to be @resource[:name] when called from an instance object.
+
+ # 10.4 doesn't support the -plist option for dscl, and 10.5 has a
+ # different format for the -url output with objects with spaces in
+ # their values. *sigh*. Use -url for 10.4 in the hope this can be
+ # deprecated one day, and use -plist for 10.5 and higher.
+ case self.get_macosx_version_major
+ when "10.4"
+ command_vector = [ command(:dscl), "-url", "." ]
+ when "10.5", "10.6"
+ command_vector = [ command(:dscl), "-plist", "." ]
+ end
+ # JJM: The actual action to perform. See "man dscl"
+ # Common actiosn: -create, -delete, -merge, -append, -passwd
+ command_vector << ds_action
+ # JJM: get_ds_path will spit back "Users" or "Groups",
+ # etc... Depending on the Puppet::Type of our self.
+ if resource_name
+ command_vector << "/#{get_ds_path}/#{resource_name}"
+ else
+ command_vector << "/#{get_ds_path}"
+ end
+ # JJM: This returns most of the preamble of the command.
+ # e.g. 'dscl / -create /Users/mccune'
+ command_vector
+ end
+
+ def self.set_password(resource_name, guid, password_hash)
+ password_hash_file = "#{@@password_hash_dir}/#{guid}"
+ begin
+ File.open(password_hash_file, 'w') { |f| f.write(password_hash)}
+ rescue Errno::EACCES => detail
+ fail("Could not write to password hash file: #{detail}")
end
- def self.get_exec_preamble(ds_action, resource_name = nil)
- # JJM 2007-07-24
- # DSCL commands are often repetitive and contain the same positional
- # arguments over and over. See http://developer.apple.com/documentation/Porting/Conceptual/PortingUnix/additionalfeatures/chapter_10_section_9.html
- # for an example of what I mean.
- # This method spits out proper DSCL commands for us.
- # We EXPECT name to be @resource[:name] when called from an instance object.
-
- # 10.4 doesn't support the -plist option for dscl, and 10.5 has a
- # different format for the -url output with objects with spaces in
- # their values. *sigh*. Use -url for 10.4 in the hope this can be
- # deprecated one day, and use -plist for 10.5 and higher.
- case self.get_macosx_version_major
- when "10.4"
- command_vector = [ command(:dscl), "-url", "." ]
- when "10.5", "10.6"
- command_vector = [ command(:dscl), "-plist", "." ]
- end
- # JJM: The actual action to perform. See "man dscl"
- # Common actiosn: -create, -delete, -merge, -append, -passwd
- command_vector << ds_action
- # JJM: get_ds_path will spit back "Users" or "Groups",
- # etc... Depending on the Puppet::Type of our self.
- if resource_name
- command_vector << "/#{get_ds_path}/#{resource_name}"
+ # NBK: For shadow hashes, the user AuthenticationAuthority must contain a value of
+ # ";ShadowHash;". The LKDC in 10.5 makes this more interesting though as it
+ # will dynamically generate ;Kerberosv5;;username@LKDC:SHA1 attributes if
+ # missing. Thus we make sure we only set ;ShadowHash; if it is missing, and
+ # we can do this with the merge command. This allows people to continue to
+ # use other custom AuthenticationAuthority attributes without stomping on them.
+ #
+ # There is a potential problem here in that we're only doing this when setting
+ # the password, and the attribute could get modified at other times while the
+ # hash doesn't change and so this doesn't get called at all... but
+ # without switching all the other attributes to merge instead of create I can't
+ # see a simple enough solution for this that doesn't modify the user record
+ # every single time. This should be a rather rare edge case. (famous last words)
+
+ dscl_vector = self.get_exec_preamble("-merge", resource_name)
+ dscl_vector << "AuthenticationAuthority" << ";ShadowHash;"
+ begin
+ dscl_output = execute(dscl_vector)
+ rescue Puppet::ExecutionFailure => detail
+ fail("Could not set AuthenticationAuthority.")
+ end
+ end
+
+ def self.get_password(guid)
+ password_hash = nil
+ password_hash_file = "#{@@password_hash_dir}/#{guid}"
+ if File.exists?(password_hash_file) and File.file?(password_hash_file)
+ fail("Could not read password hash file at #{password_hash_file}") if not File.readable?(password_hash_file)
+ f = File.new(password_hash_file)
+ password_hash = f.read
+ f.close
+ end
+ password_hash
+ end
+
+ def ensure=(ensure_value)
+ super
+ # We need to loop over all valid properties for the type we're
+ # managing and call the method which sets that property value
+ # dscl can't create everything at once unfortunately.
+ if ensure_value == :present
+ @resource.class.validproperties.each do |name|
+ next if name == :ensure
+ # LAK: We use property.sync here rather than directly calling
+ # the settor method because the properties might do some kind
+ # of conversion. In particular, the user gid property might
+ # have a string and need to convert it to a number
+ if @resource.should(name)
+ @resource.property(name).sync
+ elsif value = autogen(name)
+ self.send(name.to_s + "=", value)
else
- command_vector << "/#{get_ds_path}"
+ next
end
- # JJM: This returns most of the preamble of the command.
- # e.g. 'dscl / -create /Users/mccune'
- command_vector
+ end
end
-
- def self.set_password(resource_name, guid, password_hash)
- password_hash_file = "#{@@password_hash_dir}/#{guid}"
- begin
- File.open(password_hash_file, 'w') { |f| f.write(password_hash)}
- rescue Errno::EACCES => detail
- fail("Could not write to password hash file: #{detail}")
- end
-
- # NBK: For shadow hashes, the user AuthenticationAuthority must contain a value of
- # ";ShadowHash;". The LKDC in 10.5 makes this more interesting though as it
- # will dynamically generate ;Kerberosv5;;username@LKDC:SHA1 attributes if
- # missing. Thus we make sure we only set ;ShadowHash; if it is missing, and
- # we can do this with the merge command. This allows people to continue to
- # use other custom AuthenticationAuthority attributes without stomping on them.
- #
- # There is a potential problem here in that we're only doing this when setting
- # the password, and the attribute could get modified at other times while the
- # hash doesn't change and so this doesn't get called at all... but
- # without switching all the other attributes to merge instead of create I can't
- # see a simple enough solution for this that doesn't modify the user record
- # every single time. This should be a rather rare edge case. (famous last words)
-
- dscl_vector = self.get_exec_preamble("-merge", resource_name)
- dscl_vector << "AuthenticationAuthority" << ";ShadowHash;"
- begin
- dscl_output = execute(dscl_vector)
- rescue Puppet::ExecutionFailure => detail
- fail("Could not set AuthenticationAuthority.")
- end
+ end
+
+ def password=(passphrase)
+ exec_arg_vector = self.class.get_exec_preamble("-read", @resource.name)
+ exec_arg_vector << @@ns_to_ds_attribute_map[:guid]
+ begin
+ guid_output = execute(exec_arg_vector)
+ guid_plist = Plist.parse_xml(guid_output)
+ # Although GeneratedUID like all DirectoryService values can be multi-valued
+ # according to the schema, in practice user accounts cannot have multiple UUIDs
+ # otherwise Bad Things Happen, so we just deal with the first value.
+ guid = guid_plist["dsAttrTypeStandard:#{@@ns_to_ds_attribute_map[:guid]}"][0]
+ self.class.set_password(@resource.name, guid, passphrase)
+ rescue Puppet::ExecutionFailure => detail
+ fail("Could not set #{param} on #{@resource.class.name}[#{@resource.name}]: #{detail}")
end
-
- def self.get_password(guid)
- password_hash = nil
- password_hash_file = "#{@@password_hash_dir}/#{guid}"
- if File.exists?(password_hash_file) and File.file?(password_hash_file)
- fail("Could not read password hash file at #{password_hash_file}") if not File.readable?(password_hash_file)
- f = File.new(password_hash_file)
- password_hash = f.read
- f.close
- end
- password_hash
+ end
+
+ # NBK: we override @parent.set as we need to execute a series of commands
+ # to deal with array values, rather than the single command nameservice.rb
+ # expects to be returned by modifycmd. Thus we don't bother defining modifycmd.
+
+ def set(param, value)
+ self.class.validate(param, value)
+ current_members = @property_value_cache_hash[:members]
+ if param == :members
+ # If we are meant to be authoritative for the group membership
+ # then remove all existing members who haven't been specified
+ # in the manifest.
+ remove_unwanted_members(current_members, value) if @resource[:auth_membership] and not current_members.nil?
+
+ # if they're not a member, make them one.
+ add_members(current_members, value)
+ else
+ exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
+ # JJM: The following line just maps the NS name to the DS name
+ # e.g. { :uid => 'UniqueID' }
+ exec_arg_vector << @@ns_to_ds_attribute_map[symbolize(param)]
+ # JJM: The following line sends the actual value to set the property to
+ exec_arg_vector << value.to_s
+ begin
+ execute(exec_arg_vector)
+ rescue Puppet::ExecutionFailure => detail
+ fail("Could not set #{param} on #{@resource.class.name}[#{@resource.name}]: #{detail}")
+ end
+ end
+ end
+
+ # NBK: we override @parent.create as we need to execute a series of commands
+ # to create objects with dscl, rather than the single command nameservice.rb
+ # expects to be returned by addcmd. Thus we don't bother defining addcmd.
+ def create
+ if exists?
+ info "already exists"
+ return nil
end
- def ensure=(ensure_value)
- super
- # We need to loop over all valid properties for the type we're
- # managing and call the method which sets that property value
- # dscl can't create everything at once unfortunately.
- if ensure_value == :present
- @resource.class.validproperties.each do |name|
- next if name == :ensure
- # LAK: We use property.sync here rather than directly calling
- # the settor method because the properties might do some kind
- # of conversion. In particular, the user gid property might
- # have a string and need to convert it to a number
- if @resource.should(name)
- @resource.property(name).sync
- elsif value = autogen(name)
- self.send(name.to_s + "=", value)
- else
- next
- end
- end
- end
+ # NBK: First we create the object with a known guid so we can set the contents
+ # of the password hash if required
+ # Shelling out sucks, but for a single use case it doesn't seem worth
+ # requiring people install a UUID library that doesn't come with the system.
+ # This should be revisited if Puppet starts managing UUIDs for other platform
+ # user records.
+ guid = %x{/usr/bin/uuidgen}.chomp
+
+ exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
+ exec_arg_vector << @@ns_to_ds_attribute_map[:guid] << guid
+ begin
+ execute(exec_arg_vector)
+ rescue Puppet::ExecutionFailure => detail
+ fail("Could not set GeneratedUID for #{@resource.class.name} #{@resource.name}: #{detail}")
end
- def password=(passphrase)
- exec_arg_vector = self.class.get_exec_preamble("-read", @resource.name)
- exec_arg_vector << @@ns_to_ds_attribute_map[:guid]
- begin
- guid_output = execute(exec_arg_vector)
- guid_plist = Plist.parse_xml(guid_output)
- # Although GeneratedUID like all DirectoryService values can be multi-valued
- # according to the schema, in practice user accounts cannot have multiple UUIDs
- # otherwise Bad Things Happen, so we just deal with the first value.
- guid = guid_plist["dsAttrTypeStandard:#{@@ns_to_ds_attribute_map[:guid]}"][0]
- self.class.set_password(@resource.name, guid, passphrase)
- rescue Puppet::ExecutionFailure => detail
- fail("Could not set #{param} on #{@resource.class.name}[#{@resource.name}]: #{detail}")
- end
+ if value = @resource.should(:password) and value != ""
+ self.class.set_password(@resource[:name], guid, value)
end
- # NBK: we override @parent.set as we need to execute a series of commands
- # to deal with array values, rather than the single command nameservice.rb
- # expects to be returned by modifycmd. Thus we don't bother defining modifycmd.
-
- def set(param, value)
- self.class.validate(param, value)
- current_members = @property_value_cache_hash[:members]
- if param == :members
- # If we are meant to be authoritative for the group membership
- # then remove all existing members who haven't been specified
- # in the manifest.
- remove_unwanted_members(current_members, value) if @resource[:auth_membership] and not current_members.nil?
-
- # if they're not a member, make them one.
- add_members(current_members, value)
+ # Now we create all the standard properties
+ Puppet::Type.type(@resource.class.name).validproperties.each do |property|
+ next if property == :ensure
+ if value = @resource.should(property) and value != ""
+ if property == :members
+ add_members(nil, value)
else
- exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
- # JJM: The following line just maps the NS name to the DS name
- # e.g. { :uid => 'UniqueID' }
- exec_arg_vector << @@ns_to_ds_attribute_map[symbolize(param)]
- # JJM: The following line sends the actual value to set the property to
- exec_arg_vector << value.to_s
- begin
- execute(exec_arg_vector)
- rescue Puppet::ExecutionFailure => detail
- fail("Could not set #{param} on #{@resource.class.name}[#{@resource.name}]: #{detail}")
- end
+ exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
+ exec_arg_vector << @@ns_to_ds_attribute_map[symbolize(property)]
+ next if property == :password # skip setting the password here
+ exec_arg_vector << value.to_s
+ begin
+ execute(exec_arg_vector)
+ rescue Puppet::ExecutionFailure => detail
+ fail("Could not create #{@resource.class.name} #{@resource.name}: #{detail}")
+ end
end
+ end
end
+ end
- # NBK: we override @parent.create as we need to execute a series of commands
- # to create objects with dscl, rather than the single command nameservice.rb
- # expects to be returned by addcmd. Thus we don't bother defining addcmd.
- def create
- if exists?
- info "already exists"
- return nil
- end
-
- # NBK: First we create the object with a known guid so we can set the contents
- # of the password hash if required
- # Shelling out sucks, but for a single use case it doesn't seem worth
- # requiring people install a UUID library that doesn't come with the system.
- # This should be revisited if Puppet starts managing UUIDs for other platform
- # user records.
- guid = %x{/usr/bin/uuidgen}.chomp
-
- exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
- exec_arg_vector << @@ns_to_ds_attribute_map[:guid] << guid
+ def remove_unwanted_members(current_members, new_members)
+ current_members.each do |member|
+ if not new_members.include?(member)
+ cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-d", member, @resource[:name]]
begin
- execute(exec_arg_vector)
+ execute(cmd)
rescue Puppet::ExecutionFailure => detail
- fail("Could not set GeneratedUID for #{@resource.class.name} #{@resource.name}: #{detail}")
- end
-
- if value = @resource.should(:password) and value != ""
- self.class.set_password(@resource[:name], guid, value)
- end
-
- # Now we create all the standard properties
- Puppet::Type.type(@resource.class.name).validproperties.each do |property|
- next if property == :ensure
- if value = @resource.should(property) and value != ""
- if property == :members
- add_members(nil, value)
- else
- exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
- exec_arg_vector << @@ns_to_ds_attribute_map[symbolize(property)]
- next if property == :password # skip setting the password here
- exec_arg_vector << value.to_s
- begin
- execute(exec_arg_vector)
- rescue Puppet::ExecutionFailure => detail
- fail("Could not create #{@resource.class.name} #{@resource.name}: #{detail}")
- end
- end
- end
+ fail("Could not remove #{member} from group: #{@resource.name}, #{detail}")
end
+ end
end
+ end
- def remove_unwanted_members(current_members, new_members)
- current_members.each do |member|
- if not new_members.include?(member)
- cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-d", member, @resource[:name]]
- begin
- execute(cmd)
- rescue Puppet::ExecutionFailure => detail
- fail("Could not remove #{member} from group: #{@resource.name}, #{detail}")
- end
- end
- end
- end
-
- def add_members(current_members, new_members)
- new_members.each do |new_member|
- if current_members.nil? or not current_members.include?(new_member)
- cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-a", new_member, @resource[:name]]
- begin
- execute(cmd)
- rescue Puppet::ExecutionFailure => detail
- fail("Could not add #{new_member} to group: #{@resource.name}, #{detail}")
- end
- end
+ def add_members(current_members, new_members)
+ new_members.each do |new_member|
+ if current_members.nil? or not current_members.include?(new_member)
+ cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-a", new_member, @resource[:name]]
+ begin
+ execute(cmd)
+ rescue Puppet::ExecutionFailure => detail
+ fail("Could not add #{new_member} to group: #{@resource.name}, #{detail}")
end
+ end
end
-
- def deletecmd
- # JJM: Like addcmd, only called when deleting the object itself
- # Note, this isn't used to delete properties of the object,
- # at least that's how I understand it...
- self.class.get_exec_preamble("-delete", @resource[:name])
- end
-
- def getinfo(refresh = false)
- # JJM 2007-07-24:
- # Override the getinfo method, which is also defined in nameservice.rb
- # This method returns and sets @infohash
- # I'm not re-factoring the name "getinfo" because this method will be
- # most likely called by nameservice.rb, which I didn't write.
- if refresh or (! defined?(@property_value_cache_hash) or ! @property_value_cache_hash)
- # JJM 2007-07-24: OK, there's a bit of magic that's about to
- # happen... Let's see how strong my grip has become... =)
- #
- # self is a provider instance of some Puppet::Type, like
- # Puppet::Type::User::ProviderDirectoryservice for the case of the
- # user type and this provider.
- #
- # self.class looks like "user provider directoryservice", if that
- # helps you ...
- #
- # self.class.resource_type is a reference to the Puppet::Type class,
- # probably Puppet::Type::User or Puppet::Type::Group, etc...
- #
- # self.class.resource_type.validproperties is a class method,
- # returning an Array of the valid properties of that specific
- # Puppet::Type.
- #
- # So... something like [:comment, :home, :password, :shell, :uid,
- # :groups, :ensure, :gid]
- #
- # Ultimately, we add :name to the list, delete :ensure from the
- # list, then report on the remaining list. Pretty whacky, ehh?
- type_properties = [:name] + self.class.resource_type.validproperties
- type_properties.delete(:ensure) if type_properties.include? :ensure
- type_properties << :guid # append GeneratedUID so we just get the report here
- @property_value_cache_hash = self.class.single_report(@resource[:name], *type_properties)
- [:uid, :gid].each do |param|
- @property_value_cache_hash[param] = @property_value_cache_hash[param].to_i if @property_value_cache_hash and @property_value_cache_hash.include?(param)
- end
- end
- @property_value_cache_hash
+ end
+
+ def deletecmd
+ # JJM: Like addcmd, only called when deleting the object itself
+ # Note, this isn't used to delete properties of the object,
+ # at least that's how I understand it...
+ self.class.get_exec_preamble("-delete", @resource[:name])
+ end
+
+ def getinfo(refresh = false)
+ # JJM 2007-07-24:
+ # Override the getinfo method, which is also defined in nameservice.rb
+ # This method returns and sets @infohash
+ # I'm not re-factoring the name "getinfo" because this method will be
+ # most likely called by nameservice.rb, which I didn't write.
+ if refresh or (! defined?(@property_value_cache_hash) or ! @property_value_cache_hash)
+ # JJM 2007-07-24: OK, there's a bit of magic that's about to
+ # happen... Let's see how strong my grip has become... =)
+ #
+ # self is a provider instance of some Puppet::Type, like
+ # Puppet::Type::User::ProviderDirectoryservice for the case of the
+ # user type and this provider.
+ #
+ # self.class looks like "user provider directoryservice", if that
+ # helps you ...
+ #
+ # self.class.resource_type is a reference to the Puppet::Type class,
+ # probably Puppet::Type::User or Puppet::Type::Group, etc...
+ #
+ # self.class.resource_type.validproperties is a class method,
+ # returning an Array of the valid properties of that specific
+ # Puppet::Type.
+ #
+ # So... something like [:comment, :home, :password, :shell, :uid,
+ # :groups, :ensure, :gid]
+ #
+ # Ultimately, we add :name to the list, delete :ensure from the
+ # list, then report on the remaining list. Pretty whacky, ehh?
+ type_properties = [:name] + self.class.resource_type.validproperties
+ type_properties.delete(:ensure) if type_properties.include? :ensure
+ type_properties << :guid # append GeneratedUID so we just get the report here
+ @property_value_cache_hash = self.class.single_report(@resource[:name], *type_properties)
+ [:uid, :gid].each do |param|
+ @property_value_cache_hash[param] = @property_value_cache_hash[param].to_i if @property_value_cache_hash and @property_value_cache_hash.include?(param)
+ end
end
+ @property_value_cache_hash
+ end
end
end
diff --git a/lib/puppet/provider/nameservice/objectadd.rb b/lib/puppet/provider/nameservice/objectadd.rb
index 25528be85..80c142982 100644
--- a/lib/puppet/provider/nameservice/objectadd.rb
+++ b/lib/puppet/provider/nameservice/objectadd.rb
@@ -2,31 +2,31 @@ require 'puppet/provider/nameservice'
class Puppet::Provider::NameService
class ObjectAdd < Puppet::Provider::NameService
- def deletecmd
- [command(:delete), @resource[:name]]
- end
-
- # Determine the flag to pass to our command.
- def flag(name)
- name = name.intern if name.is_a? String
- self.class.option(name, :flag) || "-" + name.to_s[0,1]
- end
+ def deletecmd
+ [command(:delete), @resource[:name]]
+ end
- def modifycmd(param, value)
- cmd = [command(:modify), flag(param), value]
- if @resource.allowdupe? && ((param == :uid) || (param == :gid and self.class.name == :groupadd))
- cmd << "-o"
- end
- cmd << @resource[:name]
+ # Determine the flag to pass to our command.
+ def flag(name)
+ name = name.intern if name.is_a? String
+ self.class.option(name, :flag) || "-" + name.to_s[0,1]
+ end
- cmd
+ def modifycmd(param, value)
+ cmd = [command(:modify), flag(param), value]
+ if @resource.allowdupe? && ((param == :uid) || (param == :gid and self.class.name == :groupadd))
+ cmd << "-o"
end
+ cmd << @resource[:name]
- def posixmethod(name)
- name = name.intern if name.is_a? String
- method = self.class.option(name, :method) || name
+ cmd
+ end
- method
- end
+ def posixmethod(name)
+ name = name.intern if name.is_a? String
+ method = self.class.option(name, :method) || name
+
+ method
+ end
end
end
diff --git a/lib/puppet/provider/nameservice/pw.rb b/lib/puppet/provider/nameservice/pw.rb
index 702d705c6..74f1a9fbb 100644
--- a/lib/puppet/provider/nameservice/pw.rb
+++ b/lib/puppet/provider/nameservice/pw.rb
@@ -2,20 +2,20 @@ require 'puppet/provider/nameservice/objectadd'
class Puppet::Provider::NameService
class PW < ObjectAdd
- def deletecmd
- [command(:pw), "#{@resource.class.name.to_s}del", @resource[:name]]
- end
+ def deletecmd
+ [command(:pw), "#{@resource.class.name.to_s}del", @resource[:name]]
+ end
- def modifycmd(param, value)
- cmd = [
- command(:pw),
- "#{@resource.class.name.to_s}mod",
- @resource[:name],
- flag(param),
- value
- ]
- cmd
- end
+ def modifycmd(param, value)
+ cmd = [
+ command(:pw),
+ "#{@resource.class.name.to_s}mod",
+ @resource[:name],
+ flag(param),
+ value
+ ]
+ cmd
+ end
end
end
diff --git a/lib/puppet/provider/package.rb b/lib/puppet/provider/package.rb
index 0ce6cca0a..2f5f67547 100644
--- a/lib/puppet/provider/package.rb
+++ b/lib/puppet/provider/package.rb
@@ -2,26 +2,26 @@
# Copyright (c) 2007. All rights reserved.
class Puppet::Provider::Package < Puppet::Provider
- # Prefetch our package list, yo.
- def self.prefetch(packages)
- instances.each do |prov|
- if pkg = packages[prov.name]
- pkg.provider = prov
- end
- end
+ # Prefetch our package list, yo.
+ def self.prefetch(packages)
+ instances.each do |prov|
+ if pkg = packages[prov.name]
+ pkg.provider = prov
+ end
end
+ end
- # Clear out the cached values.
- def flush
- @property_hash.clear
- end
+ # Clear out the cached values.
+ def flush
+ @property_hash.clear
+ end
- # Look up the current status.
- def properties
- if @property_hash.empty?
- @property_hash = query || {:ensure => :absent}
- @property_hash[:ensure] = :absent if @property_hash.empty?
- end
- @property_hash.dup
+ # Look up the current status.
+ def properties
+ if @property_hash.empty?
+ @property_hash = query || {:ensure => :absent}
+ @property_hash[:ensure] = :absent if @property_hash.empty?
end
+ @property_hash.dup
+ end
end
diff --git a/lib/puppet/provider/package/aix.rb b/lib/puppet/provider/package/aix.rb
index dce4ccb42..134a84526 100644
--- a/lib/puppet/provider/package/aix.rb
+++ b/lib/puppet/provider/package/aix.rb
@@ -2,127 +2,127 @@ require 'puppet/provider/package'
require 'puppet/util/package'
Puppet::Type.type(:package).provide :aix, :parent => Puppet::Provider::Package do
- desc "Installation from AIX Software directory"
+ desc "Installation from AIX Software directory"
- # The commands we are using on an AIX box are installed standard
- # (except nimclient) nimclient needs the bos.sysmgt.nim.client fileset.
- commands :lslpp => "/usr/bin/lslpp",
- :installp => "/usr/sbin/installp"
+ # The commands we are using on an AIX box are installed standard
+ # (except nimclient) nimclient needs the bos.sysmgt.nim.client fileset.
+ commands :lslpp => "/usr/bin/lslpp",
+ :installp => "/usr/sbin/installp"
- # AIX supports versionable packages with and without a NIM server
- has_feature :versionable
+ # AIX supports versionable packages with and without a NIM server
+ has_feature :versionable
- confine :operatingsystem => [ :aix ]
- defaultfor :operatingsystem => :aix
+ confine :operatingsystem => [ :aix ]
+ defaultfor :operatingsystem => :aix
- attr_accessor :latest_info
+ attr_accessor :latest_info
- def self.srclistcmd(source)
- [ command(:installp), "-L", "-d", source ]
- end
-
- def self.prefetch(packages)
- raise Puppet::Error, "The aix provider can only be used by root" if Process.euid != 0
+ def self.srclistcmd(source)
+ [ command(:installp), "-L", "-d", source ]
+ end
- return unless packages.detect { |name, package| package.should(:ensure) == :latest }
+ def self.prefetch(packages)
+ raise Puppet::Error, "The aix provider can only be used by root" if Process.euid != 0
- sources = packages.collect { |name, package| package[:source] }.uniq
+ return unless packages.detect { |name, package| package.should(:ensure) == :latest }
- updates = {}
- sources.each do |source|
- execute(self.srclistcmd(source)).each do |line|
- if line =~ /^[^#][^:]*:([^:]*):([^:]*)/
- current = {}
- current[:name] = $1
- current[:version] = $2
- current[:source] = source
+ sources = packages.collect { |name, package| package[:source] }.uniq
- if updates.key?(current[:name])
- previous = updates[current[:name]]
+ updates = {}
+ sources.each do |source|
+ execute(self.srclistcmd(source)).each do |line|
+ if line =~ /^[^#][^:]*:([^:]*):([^:]*)/
+ current = {}
+ current[:name] = $1
+ current[:version] = $2
+ current[:source] = source
- updates[ current[:name] ] = current unless Puppet::Util::Package.versioncmp(previous[:version], current[:version]) == 1
+ if updates.key?(current[:name])
+ previous = updates[current[:name]]
- else
- updates[current[:name]] = current
- end
- end
- end
- end
+ updates[ current[:name] ] = current unless Puppet::Util::Package.versioncmp(previous[:version], current[:version]) == 1
- packages.each do |name, package|
- if info = updates[package[:name]]
- package.provider.latest_info = info[0]
- end
+ else
+ updates[current[:name]] = current
+ end
end
+ end
end
- def uninstall
- # Automatically process dependencies when installing/uninstalling
- # with the -g option to installp.
- installp "-gu", @resource[:name]
+ packages.each do |name, package|
+ if info = updates[package[:name]]
+ package.provider.latest_info = info[0]
+ end
end
+ end
- def install(useversion = true)
- unless source = @resource[:source]
- self.fail "A directory is required which will be used to find packages"
- end
+ def uninstall
+ # Automatically process dependencies when installing/uninstalling
+ # with the -g option to installp.
+ installp "-gu", @resource[:name]
+ end
- pkg = @resource[:name]
+ def install(useversion = true)
+ unless source = @resource[:source]
+ self.fail "A directory is required which will be used to find packages"
+ end
- pkg << " #{@resource.should(:ensure)}" if (! @resource.should(:ensure).is_a? Symbol) and useversion
+ pkg = @resource[:name]
- installp "-acgwXY", "-d", source, pkg
- end
+ pkg << " #{@resource.should(:ensure)}" if (! @resource.should(:ensure).is_a? Symbol) and useversion
- def self.pkglist(hash = {})
- cmd = [command(:lslpp), "-qLc"]
+ installp "-acgwXY", "-d", source, pkg
+ end
- if name = hash[:pkgname]
- cmd << name
- end
+ def self.pkglist(hash = {})
+ cmd = [command(:lslpp), "-qLc"]
- begin
- list = execute(cmd).scan(/^[^#][^:]*:([^:]*):([^:]*)/).collect { |n,e|
- { :name => n, :ensure => e, :provider => self.name }
- }
- rescue Puppet::ExecutionFailure => detail
- if hash[:pkgname]
- return nil
- else
- raise Puppet::Error, "Could not list installed Packages: #{detail}"
- end
- end
+ if name = hash[:pkgname]
+ cmd << name
+ end
- if hash[:pkgname]
- return list.shift
- else
- return list
- end
+ begin
+ list = execute(cmd).scan(/^[^#][^:]*:([^:]*):([^:]*)/).collect { |n,e|
+ { :name => n, :ensure => e, :provider => self.name }
+ }
+ rescue Puppet::ExecutionFailure => detail
+ if hash[:pkgname]
+ return nil
+ else
+ raise Puppet::Error, "Could not list installed Packages: #{detail}"
+ end
end
- def self.instances
- pkglist.collect do |hash|
- new(hash)
- end
+ if hash[:pkgname]
+ return list.shift
+ else
+ return list
+ end
+ end
+
+ def self.instances
+ pkglist.collect do |hash|
+ new(hash)
end
+ end
- def latest
- upd = latest_info
+ def latest
+ upd = latest_info
- unless upd.nil?
- return "#{upd[:version]}"
- else
- raise Puppet::DevError, "Tried to get latest on a missing package" if properties[:ensure] == :absent
+ unless upd.nil?
+ return "#{upd[:version]}"
+ else
+ raise Puppet::DevError, "Tried to get latest on a missing package" if properties[:ensure] == :absent
- return properties[:ensure]
- end
+ return properties[:ensure]
end
+ end
- def query
- self.class.pkglist(:pkgname => @resource[:name])
- end
+ def query
+ self.class.pkglist(:pkgname => @resource[:name])
+ end
- def update
- self.install(false)
- end
+ def update
+ self.install(false)
+ end
end
diff --git a/lib/puppet/provider/package/appdmg.rb b/lib/puppet/provider/package/appdmg.rb
index 11858114d..a49700ef1 100644
--- a/lib/puppet/provider/package/appdmg.rb
+++ b/lib/puppet/provider/package/appdmg.rb
@@ -14,97 +14,97 @@
require 'puppet/provider/package'
Puppet::Type.type(:package).provide(:appdmg, :parent => Puppet::Provider::Package) do
- desc "Package management which copies application bundles to a target."
+ desc "Package management which copies application bundles to a target."
- confine :operatingsystem => :darwin
+ confine :operatingsystem => :darwin
- commands :hdiutil => "/usr/bin/hdiutil"
- commands :curl => "/usr/bin/curl"
- commands :ditto => "/usr/bin/ditto"
+ commands :hdiutil => "/usr/bin/hdiutil"
+ commands :curl => "/usr/bin/curl"
+ commands :ditto => "/usr/bin/ditto"
- # JJM We store a cookie for each installed .app.dmg in /var/db
- def self.instances_by_name
- Dir.entries("/var/db").find_all { |f|
- f =~ /^\.puppet_appdmg_installed_/
- }.collect do |f|
- name = f.sub(/^\.puppet_appdmg_installed_/, '')
- yield name if block_given?
- name
- end
+ # JJM We store a cookie for each installed .app.dmg in /var/db
+ def self.instances_by_name
+ Dir.entries("/var/db").find_all { |f|
+ f =~ /^\.puppet_appdmg_installed_/
+ }.collect do |f|
+ name = f.sub(/^\.puppet_appdmg_installed_/, '')
+ yield name if block_given?
+ name
end
+ end
- def self.instances
- instances_by_name.collect do |name|
- new(:name => name, :provider => :appdmg, :ensure => :installed)
- end
+ def self.instances
+ instances_by_name.collect do |name|
+ new(:name => name, :provider => :appdmg, :ensure => :installed)
end
+ end
- def self.installapp(source, name, orig_source)
- appname = File.basename(source);
- ditto "--rsrc", source, "/Applications/#{appname}"
- File.open("/var/db/.puppet_appdmg_installed_#{name}", "w") do |t|
- t.print "name: '#{name}'\n"
- t.print "source: '#{orig_source}'\n"
- end
+ def self.installapp(source, name, orig_source)
+ appname = File.basename(source);
+ ditto "--rsrc", source, "/Applications/#{appname}"
+ File.open("/var/db/.puppet_appdmg_installed_#{name}", "w") do |t|
+ t.print "name: '#{name}'\n"
+ t.print "source: '#{orig_source}'\n"
end
+ end
- def self.installpkgdmg(source, name)
- unless source =~ /\.dmg$/i
- self.fail "Mac OS X PKG DMG's must specificy a source string ending in .dmg"
- end
- require 'open-uri'
- require 'facter/util/plist'
+ def self.installpkgdmg(source, name)
+ unless source =~ /\.dmg$/i
+ self.fail "Mac OS X PKG DMG's must specificy a source string ending in .dmg"
+ end
+ require 'open-uri'
+ require 'facter/util/plist'
+ cached_source = source
+ if %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ cached_source
+ cached_source = "/tmp/#{name}"
+ begin
+ curl "-o", cached_source, "-C", "-", "-k", "-s", "--url", source
+ Puppet.debug "Success: curl transfered [#{name}]"
+ rescue Puppet::ExecutionFailure
+ Puppet.debug "curl did not transfer [#{name}]. Falling back to slower open-uri transfer methods."
cached_source = source
- if %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ cached_source
- cached_source = "/tmp/#{name}"
- begin
- curl "-o", cached_source, "-C", "-", "-k", "-s", "--url", source
- Puppet.debug "Success: curl transfered [#{name}]"
- rescue Puppet::ExecutionFailure
- Puppet.debug "curl did not transfer [#{name}]. Falling back to slower open-uri transfer methods."
- cached_source = source
- end
- end
+ end
+ end
- begin
- open(cached_source) do |dmg|
- xml_str = hdiutil "mount", "-plist", "-nobrowse", "-readonly", "-mountrandom", "/tmp", dmg.path
- ptable = Plist::parse_xml xml_str
- # JJM Filter out all mount-paths into a single array, discard the rest.
- mounts = ptable['system-entities'].collect { |entity|
- entity['mount-point']
- }.select { |mountloc|; mountloc }
- begin
- mounts.each do |fspath|
- Dir.entries(fspath).select { |f|
- f =~ /\.app$/i
- }.each do |pkg|
- installapp("#{fspath}/#{pkg}", name, source)
- end
- end
- ensure
- hdiutil "eject", mounts[0]
- end
+ begin
+ open(cached_source) do |dmg|
+ xml_str = hdiutil "mount", "-plist", "-nobrowse", "-readonly", "-mountrandom", "/tmp", dmg.path
+ ptable = Plist::parse_xml xml_str
+ # JJM Filter out all mount-paths into a single array, discard the rest.
+ mounts = ptable['system-entities'].collect { |entity|
+ entity['mount-point']
+ }.select { |mountloc|; mountloc }
+ begin
+ mounts.each do |fspath|
+ Dir.entries(fspath).select { |f|
+ f =~ /\.app$/i
+ }.each do |pkg|
+ installapp("#{fspath}/#{pkg}", name, source)
+ end
end
- ensure
- # JJM Remove the file if open-uri didn't already do so.
- File.unlink(cached_source) if File.exist?(cached_source)
- end
+ ensure
+ hdiutil "eject", mounts[0]
+ end
+ end
+ ensure
+ # JJM Remove the file if open-uri didn't already do so.
+ File.unlink(cached_source) if File.exist?(cached_source)
end
+ end
- def query
- FileTest.exists?("/var/db/.puppet_appdmg_installed_#{@resource[:name]}") ? {:name => @resource[:name], :ensure => :present} : nil
- end
+ def query
+ FileTest.exists?("/var/db/.puppet_appdmg_installed_#{@resource[:name]}") ? {:name => @resource[:name], :ensure => :present} : nil
+ end
- def install
- source = nil
- unless source = @resource[:source]
- self.fail "Mac OS X PKG DMG's must specify a package source."
- end
- unless name = @resource[:name]
- self.fail "Mac OS X PKG DMG's must specify a package name."
- end
- self.class.installpkgdmg(source,name)
+ def install
+ source = nil
+ unless source = @resource[:source]
+ self.fail "Mac OS X PKG DMG's must specify a package source."
+ end
+ unless name = @resource[:name]
+ self.fail "Mac OS X PKG DMG's must specify a package name."
end
+ self.class.installpkgdmg(source,name)
+ end
end
diff --git a/lib/puppet/provider/package/apple.rb b/lib/puppet/provider/package/apple.rb
index 613e14e5e..0946de47f 100755
--- a/lib/puppet/provider/package/apple.rb
+++ b/lib/puppet/provider/package/apple.rb
@@ -2,50 +2,50 @@ require 'puppet/provider/package'
# OS X Packaging sucks. We can install packages, but that's about it.
Puppet::Type.type(:package).provide :apple, :parent => Puppet::Provider::Package do
- desc "Package management based on OS X's builtin packaging system. This is
- essentially the simplest and least functional package system in existence --
- it only supports installation; no deletion or upgrades. The provider will
- automatically add the ``.pkg`` extension, so leave that off when specifying
- the package name."
+ desc "Package management based on OS X's builtin packaging system. This is
+ essentially the simplest and least functional package system in existence --
+ it only supports installation; no deletion or upgrades. The provider will
+ automatically add the ``.pkg`` extension, so leave that off when specifying
+ the package name."
- confine :operatingsystem => :darwin
- commands :installer => "/usr/sbin/installer"
+ confine :operatingsystem => :darwin
+ commands :installer => "/usr/sbin/installer"
- def self.instances
- instance_by_name.collect do |name|
+ def self.instances
+ instance_by_name.collect do |name|
- self.new(
+ self.new(
- :name => name,
- :provider => :apple,
+ :name => name,
+ :provider => :apple,
- :ensure => :installed
- )
- end
+ :ensure => :installed
+ )
end
-
- def self.instance_by_name
- Dir.entries("/Library/Receipts").find_all { |f|
- f =~ /\.pkg$/
- }.collect { |f|
- name = f.sub(/\.pkg/, '')
- yield name if block_given?
-
- name
- }
- end
-
- def query
- FileTest.exists?("/Library/Receipts/#{@resource[:name]}.pkg") ? {:name => @resource[:name], :ensure => :present} : nil
+ end
+
+ def self.instance_by_name
+ Dir.entries("/Library/Receipts").find_all { |f|
+ f =~ /\.pkg$/
+ }.collect { |f|
+ name = f.sub(/\.pkg/, '')
+ yield name if block_given?
+
+ name
+ }
+ end
+
+ def query
+ FileTest.exists?("/Library/Receipts/#{@resource[:name]}.pkg") ? {:name => @resource[:name], :ensure => :present} : nil
+ end
+
+ def install
+ source = nil
+ unless source = @resource[:source]
+ self.fail "Mac OS X packages must specify a package source"
end
- def install
- source = nil
- unless source = @resource[:source]
- self.fail "Mac OS X packages must specify a package source"
- end
-
- installer "-pkg", source, "-target", "/"
- end
+ installer "-pkg", source, "-target", "/"
+ end
end
diff --git a/lib/puppet/provider/package/apt.rb b/lib/puppet/provider/package/apt.rb
index deab23428..d055e7552 100755
--- a/lib/puppet/provider/package/apt.rb
+++ b/lib/puppet/provider/package/apt.rb
@@ -1,108 +1,108 @@
Puppet::Type.type(:package).provide :apt, :parent => :dpkg, :source => :dpkg do
- # Provide sorting functionality
- include Puppet::Util::Package
+ # Provide sorting functionality
+ include Puppet::Util::Package
- desc "Package management via ``apt-get``."
+ desc "Package management via ``apt-get``."
- has_feature :versionable
+ has_feature :versionable
- commands :aptget => "/usr/bin/apt-get"
- commands :aptcache => "/usr/bin/apt-cache"
- commands :preseed => "/usr/bin/debconf-set-selections"
+ commands :aptget => "/usr/bin/apt-get"
+ commands :aptcache => "/usr/bin/apt-cache"
+ commands :preseed => "/usr/bin/debconf-set-selections"
- defaultfor :operatingsystem => [:debian, :ubuntu]
+ defaultfor :operatingsystem => [:debian, :ubuntu]
- ENV['DEBIAN_FRONTEND'] = "noninteractive"
+ ENV['DEBIAN_FRONTEND'] = "noninteractive"
- # A derivative of DPKG; this is how most people actually manage
- # Debian boxes, and the only thing that differs is that it can
- # install packages from remote sites.
+ # A derivative of DPKG; this is how most people actually manage
+ # Debian boxes, and the only thing that differs is that it can
+ # install packages from remote sites.
- def checkforcdrom
- unless defined?(@@checkedforcdrom)
- if FileTest.exists? "/etc/apt/sources.list"
- @@checkedforcdrom = !!(File.read("/etc/apt/sources.list") =~ /^[^#]*cdrom:/)
- else
- # This is basically a pathalogical case, but we'll just
- # ignore it
- @@checkedforcdrom = false
- end
- end
+ def checkforcdrom
+ unless defined?(@@checkedforcdrom)
+ if FileTest.exists? "/etc/apt/sources.list"
+ @@checkedforcdrom = !!(File.read("/etc/apt/sources.list") =~ /^[^#]*cdrom:/)
+ else
+ # This is basically a pathalogical case, but we'll just
+ # ignore it
+ @@checkedforcdrom = false
+ end
+ end
- if @@checkedforcdrom and @resource[:allowcdrom] != :true
- raise Puppet::Error,
- "/etc/apt/sources.list contains a cdrom source; not installing. Use 'allowcdrom' to override this failure."
- end
+ if @@checkedforcdrom and @resource[:allowcdrom] != :true
+ raise Puppet::Error,
+ "/etc/apt/sources.list contains a cdrom source; not installing. Use 'allowcdrom' to override this failure."
+ end
+ end
+
+ # Install a package using 'apt-get'. This function needs to support
+ # installing a specific version.
+ def install
+ self.run_preseed if @resource[:responsefile]
+ should = @resource[:ensure]
+
+ checkforcdrom
+ cmd = %w{-q -y}
+
+ keep = ""
+ if config = @resource[:configfiles]
+ if config == :keep
+ cmd << "-o" << 'DPkg::Options::=--force-confold'
+ else
+ cmd << "-o" << 'DPkg::Options::=--force-confnew'
+ end
end
- # Install a package using 'apt-get'. This function needs to support
- # installing a specific version.
- def install
- self.run_preseed if @resource[:responsefile]
- should = @resource[:ensure]
-
- checkforcdrom
- cmd = %w{-q -y}
-
- keep = ""
- if config = @resource[:configfiles]
- if config == :keep
- cmd << "-o" << 'DPkg::Options::=--force-confold'
- else
- cmd << "-o" << 'DPkg::Options::=--force-confnew'
- end
- end
-
- str = @resource[:name]
- case should
- when true, false, Symbol
- # pass
- else
- # Add the package version and --force-yes option
- str += "=#{should}"
- cmd << "--force-yes"
- end
-
- cmd << :install << str
-
- aptget(*cmd)
+ str = @resource[:name]
+ case should
+ when true, false, Symbol
+ # pass
+ else
+ # Add the package version and --force-yes option
+ str += "=#{should}"
+ cmd << "--force-yes"
end
- # What's the latest package version available?
- def latest
- output = aptcache :policy, @resource[:name]
+ cmd << :install << str
- if output =~ /Candidate:\s+(\S+)\s/
- return $1
- else
- self.err "Could not find latest version"
- return nil
- end
- end
+ aptget(*cmd)
+ end
- #
- # preseeds answers to dpkg-set-selection from the "responsefile"
- #
- def run_preseed
- if response = @resource[:responsefile] and FileTest.exist?(response)
- self.info("Preseeding #{response} to debconf-set-selections")
-
- preseed response
- else
- self.info "No responsefile specified or non existant, not preseeding anything"
- end
- end
+ # What's the latest package version available?
+ def latest
+ output = aptcache :policy, @resource[:name]
- def uninstall
- self.run_preseed if @resource[:responsefile]
- aptget "-y", "-q", :remove, @resource[:name]
+ if output =~ /Candidate:\s+(\S+)\s/
+ return $1
+ else
+ self.err "Could not find latest version"
+ return nil
end
-
- def purge
- self.run_preseed if @resource[:responsefile]
- aptget '-y', '-q', :remove, '--purge', @resource[:name]
- # workaround a "bug" in apt, that already removed packages are not purged
- super
+ end
+
+ #
+ # preseeds answers to dpkg-set-selection from the "responsefile"
+ #
+ def run_preseed
+ if response = @resource[:responsefile] and FileTest.exist?(response)
+ self.info("Preseeding #{response} to debconf-set-selections")
+
+ preseed response
+ else
+ self.info "No responsefile specified or non existant, not preseeding anything"
end
+ end
+
+ def uninstall
+ self.run_preseed if @resource[:responsefile]
+ aptget "-y", "-q", :remove, @resource[:name]
+ end
+
+ def purge
+ self.run_preseed if @resource[:responsefile]
+ aptget '-y', '-q', :remove, '--purge', @resource[:name]
+ # workaround a "bug" in apt, that already removed packages are not purged
+ super
+ end
end
diff --git a/lib/puppet/provider/package/aptitude.rb b/lib/puppet/provider/package/aptitude.rb
index 5529535de..557e657a4 100755
--- a/lib/puppet/provider/package/aptitude.rb
+++ b/lib/puppet/provider/package/aptitude.rb
@@ -1,29 +1,29 @@
Puppet::Type.type(:package).provide :aptitude, :parent => :apt, :source => :dpkg do
- desc "Package management via ``aptitude``."
+ desc "Package management via ``aptitude``."
- has_feature :versionable
+ has_feature :versionable
- commands :aptitude => "/usr/bin/aptitude"
- commands :aptcache => "/usr/bin/apt-cache"
+ commands :aptitude => "/usr/bin/aptitude"
+ commands :aptcache => "/usr/bin/apt-cache"
- ENV['DEBIAN_FRONTEND'] = "noninteractive"
+ ENV['DEBIAN_FRONTEND'] = "noninteractive"
- def aptget(*args)
- args.flatten!
- # Apparently aptitude hasn't always supported a -q flag.
- args.delete("-q") if args.include?("-q")
- output = aptitude(*args)
+ def aptget(*args)
+ args.flatten!
+ # Apparently aptitude hasn't always supported a -q flag.
+ args.delete("-q") if args.include?("-q")
+ output = aptitude(*args)
- # Yay, stupid aptitude doesn't throw an error when the package is missing.
- if args.include?(:install) and output =~ /Couldn't find any package/
- raise Puppet::Error.new(
- "Could not find package #{self.name}"
- )
- end
+ # Yay, stupid aptitude doesn't throw an error when the package is missing.
+ if args.include?(:install) and output =~ /Couldn't find any package/
+ raise Puppet::Error.new(
+ "Could not find package #{self.name}"
+ )
end
+ end
- def purge
- aptitude '-y', 'purge', @resource[:name]
- end
+ def purge
+ aptitude '-y', 'purge', @resource[:name]
+ end
end
diff --git a/lib/puppet/provider/package/aptrpm.rb b/lib/puppet/provider/package/aptrpm.rb
index 42f7e706c..d7842089f 100644
--- a/lib/puppet/provider/package/aptrpm.rb
+++ b/lib/puppet/provider/package/aptrpm.rb
@@ -1,84 +1,84 @@
Puppet::Type.type(:package).provide :aptrpm, :parent => :rpm, :source => :rpm do
- # Provide sorting functionality
- include Puppet::Util::Package
-
- desc "Package management via ``apt-get`` ported to ``rpm``."
-
- has_feature :versionable
-
- commands :aptget => "apt-get"
- commands :aptcache => "apt-cache"
- commands :rpm => "rpm"
-
- if command('rpm')
- confine :true => begin
- rpm('-ql', 'rpm')
- rescue Puppet::ExecutionFailure
- false
- else
- true
- end
+ # Provide sorting functionality
+ include Puppet::Util::Package
+
+ desc "Package management via ``apt-get`` ported to ``rpm``."
+
+ has_feature :versionable
+
+ commands :aptget => "apt-get"
+ commands :aptcache => "apt-cache"
+ commands :rpm => "rpm"
+
+ if command('rpm')
+ confine :true => begin
+ rpm('-ql', 'rpm')
+ rescue Puppet::ExecutionFailure
+ false
+ else
+ true
+ end
+ end
+
+ # Install a package using 'apt-get'. This function needs to support
+ # installing a specific version.
+ def install
+ should = @resource.should(:ensure)
+
+ str = @resource[:name]
+ case should
+ when true, false, Symbol
+ # pass
+ else
+ # Add the package version
+ str += "=#{should}"
end
+ cmd = %w{-q -y}
- # Install a package using 'apt-get'. This function needs to support
- # installing a specific version.
- def install
- should = @resource.should(:ensure)
+ cmd << 'install' << str
- str = @resource[:name]
- case should
- when true, false, Symbol
- # pass
- else
- # Add the package version
- str += "=#{should}"
- end
- cmd = %w{-q -y}
+ aptget(*cmd)
+ end
- cmd << 'install' << str
+ # What's the latest package version available?
+ def latest
+ output = aptcache :showpkg, @resource[:name]
- aptget(*cmd)
- end
-
- # What's the latest package version available?
- def latest
- output = aptcache :showpkg, @resource[:name]
-
- if output =~ /Versions:\s*\n((\n|.)+)^$/
- versions = $1
- available_versions = versions.split(/\n/).collect { |version|
- if version =~ /^([^\(]+)\(/
- $1
- else
- self.warning "Could not match version '#{version}'"
- nil
- end
- }.reject { |vers| vers.nil? }.sort { |a,b|
- versioncmp(a,b)
- }
-
- if available_versions.length == 0
- self.debug "No latest version"
- print output if Puppet[:debug]
- end
-
- # Get the latest and greatest version number
- return available_versions.pop
+ if output =~ /Versions:\s*\n((\n|.)+)^$/
+ versions = $1
+ available_versions = versions.split(/\n/).collect { |version|
+ if version =~ /^([^\(]+)\(/
+ $1
else
- self.err "Could not match string"
+ self.warning "Could not match version '#{version}'"
+ nil
end
+ }.reject { |vers| vers.nil? }.sort { |a,b|
+ versioncmp(a,b)
+ }
+
+ if available_versions.length == 0
+ self.debug "No latest version"
+ print output if Puppet[:debug]
+ end
+
+ # Get the latest and greatest version number
+ return available_versions.pop
+ else
+ self.err "Could not match string"
end
+ end
- def update
- self.install
- end
+ def update
+ self.install
+ end
- def uninstall
- aptget "-y", "-q", 'remove', @resource[:name]
- end
+ def uninstall
+ aptget "-y", "-q", 'remove', @resource[:name]
+ end
- def purge
- aptget '-y', '-q', 'remove', '--purge', @resource[:name]
- end
+ def purge
+ aptget '-y', '-q', 'remove', '--purge', @resource[:name]
+ end
end
diff --git a/lib/puppet/provider/package/blastwave.rb b/lib/puppet/provider/package/blastwave.rb
index d1cfe6f2b..9f1f1ec19 100755
--- a/lib/puppet/provider/package/blastwave.rb
+++ b/lib/puppet/provider/package/blastwave.rb
@@ -1,112 +1,112 @@
# Packaging using Blastwave's pkg-get program.
Puppet::Type.type(:package).provide :blastwave, :parent => :sun, :source => :sun do
- desc "Package management using Blastwave.org's ``pkg-get`` command on Solaris."
- pkgget = "pkg-get"
- pkgget = "/opt/csw/bin/pkg-get" if FileTest.executable?("/opt/csw/bin/pkg-get")
+ desc "Package management using Blastwave.org's ``pkg-get`` command on Solaris."
+ pkgget = "pkg-get"
+ pkgget = "/opt/csw/bin/pkg-get" if FileTest.executable?("/opt/csw/bin/pkg-get")
- confine :operatingsystem => :solaris
+ confine :operatingsystem => :solaris
- commands :pkgget => pkgget
+ commands :pkgget => pkgget
- def pkgget_with_cat(*args)
- Puppet::Util::Execution::withenv(:PAGER => "/usr/bin/cat") { pkgget(*args) }
- end
-
- def self.extended(mod)
- unless command(:pkgget) != "pkg-get"
- raise Puppet::Error,
- "The pkg-get command is missing; blastwave packaging unavailable"
- end
+ def pkgget_with_cat(*args)
+ Puppet::Util::Execution::withenv(:PAGER => "/usr/bin/cat") { pkgget(*args) }
+ end
- unless FileTest.exists?("/var/pkg-get/admin")
- Puppet.notice "It is highly recommended you create '/var/pkg-get/admin'."
- Puppet.notice "See /var/pkg-get/admin-fullauto"
- end
+ def self.extended(mod)
+ unless command(:pkgget) != "pkg-get"
+ raise Puppet::Error,
+ "The pkg-get command is missing; blastwave packaging unavailable"
end
- def self.instances(hash = {})
- blastlist(hash).collect do |bhash|
- bhash.delete(:avail)
- new(bhash)
- end
+ unless FileTest.exists?("/var/pkg-get/admin")
+ Puppet.notice "It is highly recommended you create '/var/pkg-get/admin'."
+ Puppet.notice "See /var/pkg-get/admin-fullauto"
end
+ end
- # Turn our blastwave listing into a bunch of hashes.
- def self.blastlist(hash)
- command = ["-c"]
-
- command << hash[:justme] if hash[:justme]
-
- output = Puppet::Util::Execution::withenv(:PAGER => "/usr/bin/cat") { pkgget command }
+ def self.instances(hash = {})
+ blastlist(hash).collect do |bhash|
+ bhash.delete(:avail)
+ new(bhash)
+ end
+ end
- list = output.split("\n").collect do |line|
- next if line =~ /^#/
- next if line =~ /^WARNING/
- next if line =~ /localrev\s+remoterev/
+ # Turn our blastwave listing into a bunch of hashes.
+ def self.blastlist(hash)
+ command = ["-c"]
- blastsplit(line)
- end.reject { |h| h.nil? }
+ command << hash[:justme] if hash[:justme]
- if hash[:justme]
- return list[0]
- else
- list.reject! { |h|
- h[:ensure] == :absent
- }
- return list
- end
+ output = Puppet::Util::Execution::withenv(:PAGER => "/usr/bin/cat") { pkgget command }
- end
+ list = output.split("\n").collect do |line|
+ next if line =~ /^#/
+ next if line =~ /^WARNING/
+ next if line =~ /localrev\s+remoterev/
- # Split the different lines into hashes.
- def self.blastsplit(line)
- if line =~ /\s*(\S+)\s+((\[Not installed\])|(\S+))\s+(\S+)/
- hash = {}
- hash[:name] = $1
- hash[:ensure] = if $2 == "[Not installed]"
- :absent
- else
- $2
- end
- hash[:avail] = $5
-
- hash[:avail] = hash[:ensure] if hash[:avail] == "SAME"
-
- # Use the name method, so it works with subclasses.
- hash[:provider] = self.name
-
- return hash
- else
- Puppet.warning "Cannot match #{line}"
- return nil
- end
- end
+ blastsplit(line)
+ end.reject { |h| h.nil? }
- def install
- pkgget_with_cat "-f", :install, @resource[:name]
+ if hash[:justme]
+ return list[0]
+ else
+ list.reject! { |h|
+ h[:ensure] == :absent
+ }
+ return list
end
- # Retrieve the version from the current package file.
- def latest
- hash = self.class.blastlist(:justme => @resource[:name])
- hash[:avail]
+ end
+
+ # Split the different lines into hashes.
+ def self.blastsplit(line)
+ if line =~ /\s*(\S+)\s+((\[Not installed\])|(\S+))\s+(\S+)/
+ hash = {}
+ hash[:name] = $1
+ hash[:ensure] = if $2 == "[Not installed]"
+ :absent
+ else
+ $2
+ end
+ hash[:avail] = $5
+
+ hash[:avail] = hash[:ensure] if hash[:avail] == "SAME"
+
+ # Use the name method, so it works with subclasses.
+ hash[:provider] = self.name
+
+ return hash
+ else
+ Puppet.warning "Cannot match #{line}"
+ return nil
end
-
- def query
- if hash = self.class.blastlist(:justme => @resource[:name])
- hash
- else
- {:ensure => :absent}
- end
+ end
+
+ def install
+ pkgget_with_cat "-f", :install, @resource[:name]
+ end
+
+ # Retrieve the version from the current package file.
+ def latest
+ hash = self.class.blastlist(:justme => @resource[:name])
+ hash[:avail]
+ end
+
+ def query
+ if hash = self.class.blastlist(:justme => @resource[:name])
+ hash
+ else
+ {:ensure => :absent}
end
+ end
- # Remove the old package, and install the new one
- def update
- pkgget_with_cat "-f", :upgrade, @resource[:name]
- end
+ # Remove the old package, and install the new one
+ def update
+ pkgget_with_cat "-f", :upgrade, @resource[:name]
+ end
- def uninstall
- pkgget_with_cat "-f", :remove, @resource[:name]
- end
+ def uninstall
+ pkgget_with_cat "-f", :remove, @resource[:name]
+ end
end
diff --git a/lib/puppet/provider/package/darwinport.rb b/lib/puppet/provider/package/darwinport.rb
index c746cc3b3..c5f9ba28f 100755
--- a/lib/puppet/provider/package/darwinport.rb
+++ b/lib/puppet/provider/package/darwinport.rb
@@ -1,86 +1,86 @@
require 'puppet/provider/package'
Puppet::Type.type(:package).provide :darwinport, :parent => Puppet::Provider::Package do
- desc "Package management using DarwinPorts on OS X."
-
- confine :operatingsystem => :darwin
- commands :port => "/opt/local/bin/port"
-
- def self.eachpkgashash
- # list out all of the packages
- open("| #{command(:port)} list installed") { |process|
- regex = %r{(\S+)\s+@(\S+)\s+(\S+)}
- fields = [:name, :ensure, :location]
- hash = {}
-
- # now turn each returned line into a package object
- process.each { |line|
- hash.clear
-
- if match = regex.match(line)
- fields.zip(match.captures) { |field,value|
- hash[field] = value
- }
-
- hash.delete :location
- hash[:provider] = self.name
- yield hash.dup
- else
- raise Puppet::DevError,
- "Failed to match dpkg line #{line}"
- end
- }
- }
- end
-
- def self.instances
- packages = []
-
- eachpkgashash do |hash|
- packages << new(hash)
+ desc "Package management using DarwinPorts on OS X."
+
+ confine :operatingsystem => :darwin
+ commands :port => "/opt/local/bin/port"
+
+ def self.eachpkgashash
+ # list out all of the packages
+ open("| #{command(:port)} list installed") { |process|
+ regex = %r{(\S+)\s+@(\S+)\s+(\S+)}
+ fields = [:name, :ensure, :location]
+ hash = {}
+
+ # now turn each returned line into a package object
+ process.each { |line|
+ hash.clear
+
+ if match = regex.match(line)
+ fields.zip(match.captures) { |field,value|
+ hash[field] = value
+ }
+
+ hash.delete :location
+ hash[:provider] = self.name
+ yield hash.dup
+ else
+ raise Puppet::DevError,
+ "Failed to match dpkg line #{line}"
end
+ }
+ }
+ end
- packages
- end
+ def self.instances
+ packages = []
- def install
- should = @resource.should(:ensure)
-
- # Seems like you can always say 'upgrade'
- output = port "upgrade", @resource[:name]
- if output =~ /^Error: No port/
- raise Puppet::ExecutionFailure, "Could not find package #{@resource[:name]}"
- end
+ eachpkgashash do |hash|
+ packages << new(hash)
end
- def query
- version = nil
- self.class.eachpkgashash do |hash|
- return hash if hash[:name] == @resource[:name]
- end
+ packages
+ end
- nil
+ def install
+ should = @resource.should(:ensure)
+
+ # Seems like you can always say 'upgrade'
+ output = port "upgrade", @resource[:name]
+ if output =~ /^Error: No port/
+ raise Puppet::ExecutionFailure, "Could not find package #{@resource[:name]}"
end
+ end
- def latest
- info = port :search, "^#{@resource[:name]}$"
+ def query
+ version = nil
+ self.class.eachpkgashash do |hash|
+ return hash if hash[:name] == @resource[:name]
+ end
- if $CHILD_STATUS != 0 or info =~ /^Error/
- return nil
- end
+ nil
+ end
- ary = info.split(/\s+/)
- version = ary[2].sub(/^@/, '')
+ def latest
+ info = port :search, "^#{@resource[:name]}$"
- version
+ if $CHILD_STATUS != 0 or info =~ /^Error/
+ return nil
end
- def uninstall
- port :uninstall, @resource[:name]
- end
+ ary = info.split(/\s+/)
+ version = ary[2].sub(/^@/, '')
- def update
- install
- end
+ version
+ end
+
+ def uninstall
+ port :uninstall, @resource[:name]
+ end
+
+ def update
+ install
+ end
end
diff --git a/lib/puppet/provider/package/dpkg.rb b/lib/puppet/provider/package/dpkg.rb
index 06d3f58f8..bee63bfba 100755
--- a/lib/puppet/provider/package/dpkg.rb
+++ b/lib/puppet/provider/package/dpkg.rb
@@ -1,156 +1,156 @@
require 'puppet/provider/package'
Puppet::Type.type(:package).provide :dpkg, :parent => Puppet::Provider::Package do
- desc "Package management via ``dpkg``. Because this only uses ``dpkg``
- and not ``apt``, you must specify the source of any packages you want
- to manage."
-
- has_feature :holdable
-
- commands :dpkg => "/usr/bin/dpkg"
- commands :dpkg_deb => "/usr/bin/dpkg-deb"
- commands :dpkgquery => "/usr/bin/dpkg-query"
-
- def self.instances
- packages = []
-
- # list out all of the packages
- cmd = "#{command(:dpkgquery)} -W --showformat '${Status} ${Package} ${Version}\\n'"
- Puppet.debug "Executing '#{cmd}'"
- execpipe(cmd) do |process|
- # our regex for matching dpkg output
- regex = %r{^(\S+) +(\S+) +(\S+) (\S+) (\S*)$}
- fields = [:desired, :error, :status, :name, :ensure]
- hash = {}
-
- # now turn each returned line into a package object
- process.each { |line|
- if hash = parse_line(line)
- packages << new(hash)
- end
- }
+ desc "Package management via ``dpkg``. Because this only uses ``dpkg``
+ and not ``apt``, you must specify the source of any packages you want
+ to manage."
+
+ has_feature :holdable
+
+ commands :dpkg => "/usr/bin/dpkg"
+ commands :dpkg_deb => "/usr/bin/dpkg-deb"
+ commands :dpkgquery => "/usr/bin/dpkg-query"
+
+ def self.instances
+ packages = []
+
+ # list out all of the packages
+ cmd = "#{command(:dpkgquery)} -W --showformat '${Status} ${Package} ${Version}\\n'"
+ Puppet.debug "Executing '#{cmd}'"
+ execpipe(cmd) do |process|
+ # our regex for matching dpkg output
+ regex = %r{^(\S+) +(\S+) +(\S+) (\S+) (\S*)$}
+ fields = [:desired, :error, :status, :name, :ensure]
+ hash = {}
+
+ # now turn each returned line into a package object
+ process.each { |line|
+ if hash = parse_line(line)
+ packages << new(hash)
end
-
- packages
+ }
end
- self::REGEX = %r{^(\S+) +(\S+) +(\S+) (\S+) (\S*)$}
- self::FIELDS = [:desired, :error, :status, :name, :ensure]
+ packages
+ end
- def self.parse_line(line)
- if match = self::REGEX.match(line)
- hash = {}
+ self::REGEX = %r{^(\S+) +(\S+) +(\S+) (\S+) (\S*)$}
+ self::FIELDS = [:desired, :error, :status, :name, :ensure]
- self::FIELDS.zip(match.captures) { |field,value|
- hash[field] = value
- }
+ def self.parse_line(line)
+ if match = self::REGEX.match(line)
+ hash = {}
- hash[:provider] = self.name
+ self::FIELDS.zip(match.captures) { |field,value|
+ hash[field] = value
+ }
- if hash[:status] == 'not-installed'
- hash[:ensure] = :purged
- elsif ['config-files', 'half-installed', 'unpacked', 'half-configured'].include?(hash[:status])
- hash[:ensure] = :absent
- end
- hash[:ensure] = :held if hash[:desired] == 'hold'
- else
- Puppet.warning "Failed to match dpkg-query line #{line.inspect}"
- return nil
- end
+ hash[:provider] = self.name
- hash
+ if hash[:status] == 'not-installed'
+ hash[:ensure] = :purged
+ elsif ['config-files', 'half-installed', 'unpacked', 'half-configured'].include?(hash[:status])
+ hash[:ensure] = :absent
+ end
+ hash[:ensure] = :held if hash[:desired] == 'hold'
+ else
+ Puppet.warning "Failed to match dpkg-query line #{line.inspect}"
+ return nil
end
- def install
- unless file = @resource[:source]
- raise ArgumentError, "You cannot install dpkg packages without a source"
- end
+ hash
+ end
- args = []
+ def install
+ unless file = @resource[:source]
+ raise ArgumentError, "You cannot install dpkg packages without a source"
+ end
- # We always unhold when installing to remove any prior hold.
- self.unhold
+ args = []
- if @resource[:configfiles] == :keep
- args << '--force-confold'
- else
- args << '--force-confnew'
- end
- args << '-i' << file
+ # We always unhold when installing to remove any prior hold.
+ self.unhold
- dpkg(*args)
+ if @resource[:configfiles] == :keep
+ args << '--force-confold'
+ else
+ args << '--force-confnew'
end
+ args << '-i' << file
- def update
- self.install
- end
+ dpkg(*args)
+ end
- # Return the version from the package.
- def latest
- output = dpkg_deb "--show", @resource[:source]
- matches = /^(\S+)\t(\S+)$/.match(output).captures
- warning "source doesn't contain named package, but #{matches[0]}" unless matches[0].match( Regexp.escape(@resource[:name]) )
- matches[1]
- end
+ def update
+ self.install
+ end
- def query
- packages = []
+ # Return the version from the package.
+ def latest
+ output = dpkg_deb "--show", @resource[:source]
+ matches = /^(\S+)\t(\S+)$/.match(output).captures
+ warning "source doesn't contain named package, but #{matches[0]}" unless matches[0].match( Regexp.escape(@resource[:name]) )
+ matches[1]
+ end
- fields = [:desired, :error, :status, :name, :ensure]
+ def query
+ packages = []
- hash = {}
+ fields = [:desired, :error, :status, :name, :ensure]
- # list out our specific package
- begin
+ hash = {}
- output = dpkgquery(
- "-W", "--showformat",
-
- '${Status} ${Package} ${Version}\\n', @resource[:name]
- )
- rescue Puppet::ExecutionFailure
- # dpkg-query exits 1 if the package is not found.
- return {:ensure => :purged, :status => 'missing', :name => @resource[:name], :error => 'ok'}
+ # list out our specific package
+ begin
- end
-
- hash = self.class.parse_line(output) || {:ensure => :absent, :status => 'missing', :name => @resource[:name], :error => 'ok'}
-
- if hash[:error] != "ok"
- raise Puppet::Error.new(
- "Package #{hash[:name]}, version #{hash[:ensure]} is in error state: #{hash[:error]}"
- )
- end
+ output = dpkgquery(
+ "-W", "--showformat",
+
+ '${Status} ${Package} ${Version}\\n', @resource[:name]
+ )
+ rescue Puppet::ExecutionFailure
+ # dpkg-query exits 1 if the package is not found.
+ return {:ensure => :purged, :status => 'missing', :name => @resource[:name], :error => 'ok'}
- hash
end
- def uninstall
- dpkg "-r", @resource[:name]
- end
+ hash = self.class.parse_line(output) || {:ensure => :absent, :status => 'missing', :name => @resource[:name], :error => 'ok'}
- def purge
- dpkg "--purge", @resource[:name]
+ if hash[:error] != "ok"
+ raise Puppet::Error.new(
+ "Package #{hash[:name]}, version #{hash[:ensure]} is in error state: #{hash[:error]}"
+ )
end
- def hold
- self.install
- begin
- Tempfile.open('puppet_dpkg_set_selection') { |tmpfile|
- tmpfile.write("#{@resource[:name]} hold\n")
- tmpfile.flush
- execute([:dpkg, "--set-selections"], :stdinfile => tmpfile.path.to_s)
- }
- end
+ hash
+ end
+
+ def uninstall
+ dpkg "-r", @resource[:name]
+ end
+
+ def purge
+ dpkg "--purge", @resource[:name]
+ end
+
+ def hold
+ self.install
+ begin
+ Tempfile.open('puppet_dpkg_set_selection') { |tmpfile|
+ tmpfile.write("#{@resource[:name]} hold\n")
+ tmpfile.flush
+ execute([:dpkg, "--set-selections"], :stdinfile => tmpfile.path.to_s)
+ }
end
-
- def unhold
- begin
- Tempfile.open('puppet_dpkg_set_selection') { |tmpfile|
- tmpfile.write("#{@resource[:name]} install\n")
- tmpfile.flush
- execute([:dpkg, "--set-selections"], :stdinfile => tmpfile.path.to_s)
- }
- end
+ end
+
+ def unhold
+ begin
+ Tempfile.open('puppet_dpkg_set_selection') { |tmpfile|
+ tmpfile.write("#{@resource[:name]} install\n")
+ tmpfile.flush
+ execute([:dpkg, "--set-selections"], :stdinfile => tmpfile.path.to_s)
+ }
end
+ end
end
diff --git a/lib/puppet/provider/package/fink.rb b/lib/puppet/provider/package/fink.rb
index a7310b00a..5cf47860e 100755
--- a/lib/puppet/provider/package/fink.rb
+++ b/lib/puppet/provider/package/fink.rb
@@ -1,82 +1,82 @@
Puppet::Type.type(:package).provide :fink, :parent => :dpkg, :source => :dpkg do
- # Provide sorting functionality
- include Puppet::Util::Package
-
- desc "Package management via ``fink``."
-
- commands :fink => "/sw/bin/fink"
- commands :aptget => "/sw/bin/apt-get"
- commands :aptcache => "/sw/bin/apt-cache"
- commands :dpkgquery => "/sw/bin/dpkg-query"
+ # Provide sorting functionality
+ include Puppet::Util::Package
+
+ desc "Package management via ``fink``."
+
+ commands :fink => "/sw/bin/fink"
+ commands :aptget => "/sw/bin/apt-get"
+ commands :aptcache => "/sw/bin/apt-cache"
+ commands :dpkgquery => "/sw/bin/dpkg-query"
+
+ has_feature :versionable
+
+ # A derivative of DPKG; this is how most people actually manage
+ # Debian boxes, and the only thing that differs is that it can
+ # install packages from remote sites.
+
+ def finkcmd(*args)
+ fink(*args)
+ end
+
+ # Install a package using 'apt-get'. This function needs to support
+ # installing a specific version.
+ def install
+ self.run_preseed if @resource[:responsefile]
+ should = @resource.should(:ensure)
+
+ str = @resource[:name]
+ case should
+ when true, false, Symbol
+ # pass
+ else
+ # Add the package version
+ str += "=#{should}"
+ end
+ cmd = %w{-b -q -y}
- has_feature :versionable
+ keep = ""
- # A derivative of DPKG; this is how most people actually manage
- # Debian boxes, and the only thing that differs is that it can
- # install packages from remote sites.
+ cmd << :install << str
- def finkcmd(*args)
- fink(*args)
- end
+ finkcmd(cmd)
+ end
- # Install a package using 'apt-get'. This function needs to support
- # installing a specific version.
- def install
- self.run_preseed if @resource[:responsefile]
- should = @resource.should(:ensure)
+ # What's the latest package version available?
+ def latest
+ output = aptcache :policy, @resource[:name]
- str = @resource[:name]
- case should
- when true, false, Symbol
- # pass
+ if output =~ /Candidate:\s+(\S+)\s/
+ return $1
else
- # Add the package version
- str += "=#{should}"
+ self.err "Could not find latest version"
+ return nil
+ end
end
- cmd = %w{-b -q -y}
-
- keep = ""
- cmd << :install << str
+ #
+ # preseeds answers to dpkg-set-selection from the "responsefile"
+ #
+ def run_preseed
+ if response = @resource[:responsefile] and FileTest.exists?(response)
+ self.info("Preseeding #{response} to debconf-set-selections")
- finkcmd(cmd)
+ preseed response
+ else
+ self.info "No responsefile specified or non existant, not preseeding anything"
end
+ end
- # What's the latest package version available?
- def latest
- output = aptcache :policy, @resource[:name]
-
- if output =~ /Candidate:\s+(\S+)\s/
- return $1
- else
- self.err "Could not find latest version"
- return nil
- end
- end
-
- #
- # preseeds answers to dpkg-set-selection from the "responsefile"
- #
- def run_preseed
- if response = @resource[:responsefile] and FileTest.exists?(response)
- self.info("Preseeding #{response} to debconf-set-selections")
-
- preseed response
- else
- self.info "No responsefile specified or non existant, not preseeding anything"
- end
- end
-
- def update
- self.install
- end
+ def update
+ self.install
+ end
- def uninstall
- finkcmd "-y", "-q", :remove, @model[:name]
- end
+ def uninstall
+ finkcmd "-y", "-q", :remove, @model[:name]
+ end
- def purge
- aptget '-y', '-q', 'remove', '--purge', @resource[:name]
- end
+ def purge
+ aptget '-y', '-q', 'remove', '--purge', @resource[:name]
+ end
end
diff --git a/lib/puppet/provider/package/freebsd.rb b/lib/puppet/provider/package/freebsd.rb
index 95d15c735..2f012a4ed 100755
--- a/lib/puppet/provider/package/freebsd.rb
+++ b/lib/puppet/provider/package/freebsd.rb
@@ -1,50 +1,50 @@
Puppet::Type.type(:package).provide :freebsd, :parent => :openbsd do
- desc "The specific form of package management on FreeBSD. This is an
- extremely quirky packaging system, in that it freely mixes between
- ports and packages. Apparently all of the tools are written in Ruby,
- so there are plans to rewrite this support to directly use those
- libraries."
+ desc "The specific form of package management on FreeBSD. This is an
+ extremely quirky packaging system, in that it freely mixes between
+ ports and packages. Apparently all of the tools are written in Ruby,
+ so there are plans to rewrite this support to directly use those
+ libraries."
- commands :pkginfo => "/usr/sbin/pkg_info",
- :pkgadd => "/usr/sbin/pkg_add",
- :pkgdelete => "/usr/sbin/pkg_delete"
+ commands :pkginfo => "/usr/sbin/pkg_info",
+ :pkgadd => "/usr/sbin/pkg_add",
+ :pkgdelete => "/usr/sbin/pkg_delete"
- confine :operatingsystem => :freebsd
+ confine :operatingsystem => :freebsd
- def self.listcmd
- command(:pkginfo)
- end
+ def self.listcmd
+ command(:pkginfo)
+ end
- def install
- should = @resource.should(:ensure)
-
- if @resource[:source] =~ /\/$/
- if @resource[:source] =~ /^(ftp|https?):/
- withenv :PACKAGESITE => @resource[:source] do
- pkgadd "-r", @resource[:name]
- end
- else
- withenv :PKG_PATH => @resource[:source] do
- pkgadd @resource[:name]
- end
- end
- else
- Puppet.warning "source is defined but does not have trailing slash, ignoring #{@resource[:source]}" if @resource[:source]
- pkgadd "-r", @resource[:name]
- end
- end
+ def install
+ should = @resource.should(:ensure)
- def query
- self.class.instances.each do |provider|
- if provider.name == @resource.name
- return provider.properties
- end
+ if @resource[:source] =~ /\/$/
+ if @resource[:source] =~ /^(ftp|https?):/
+ withenv :PACKAGESITE => @resource[:source] do
+ pkgadd "-r", @resource[:name]
end
- nil
+ else
+ withenv :PKG_PATH => @resource[:source] do
+ pkgadd @resource[:name]
+ end
+ end
+ else
+ Puppet.warning "source is defined but does not have trailing slash, ignoring #{@resource[:source]}" if @resource[:source]
+ pkgadd "-r", @resource[:name]
end
+ end
- def uninstall
- pkgdelete "#{@resource[:name]}-#{@resource.should(:ensure)}"
+ def query
+ self.class.instances.each do |provider|
+ if provider.name == @resource.name
+ return provider.properties
+ end
end
+ nil
+ end
+
+ def uninstall
+ pkgdelete "#{@resource[:name]}-#{@resource.should(:ensure)}"
+ end
end
diff --git a/lib/puppet/provider/package/gem.rb b/lib/puppet/provider/package/gem.rb
index 90b436fa6..8d70b756f 100755
--- a/lib/puppet/provider/package/gem.rb
+++ b/lib/puppet/provider/package/gem.rb
@@ -3,122 +3,122 @@ require 'uri'
# Ruby gems support.
Puppet::Type.type(:package).provide :gem, :parent => Puppet::Provider::Package do
- desc "Ruby Gem support. If a URL is passed via ``source``, then that URL is used as the
- remote gem repository; if a source is present but is not a valid URL, it will be
- interpreted as the path to a local gem file. If source is not present at all,
- the gem will be installed from the default gem repositories."
+ desc "Ruby Gem support. If a URL is passed via ``source``, then that URL is used as the
+ remote gem repository; if a source is present but is not a valid URL, it will be
+ interpreted as the path to a local gem file. If source is not present at all,
+ the gem will be installed from the default gem repositories."
- has_feature :versionable
+ has_feature :versionable
- commands :gemcmd => "gem"
+ commands :gemcmd => "gem"
- def self.gemlist(hash)
- command = [command(:gemcmd), "list"]
+ def self.gemlist(hash)
+ command = [command(:gemcmd), "list"]
- if hash[:local]
- command << "--local"
- else
- command << "--remote"
- end
-
- if name = hash[:justme]
- command << name
- end
-
- begin
- list = execute(command).split("\n").collect do |set|
- if gemhash = gemsplit(set)
- gemhash[:provider] = :gem
- gemhash
- else
- nil
- end
- end.compact
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not list gems: #{detail}"
- end
+ if hash[:local]
+ command << "--local"
+ else
+ command << "--remote"
+ end
- if hash[:justme]
- return list.shift
- else
- return list
- end
+ if name = hash[:justme]
+ command << name
end
- def self.gemsplit(desc)
- case desc
- when /^\*\*\*/, /^\s*$/, /^\s+/; return nil
- when /^(\S+)\s+\((.+)\)/
- name = $1
- version = $2.split(/,\s*/)[0]
- return {
- :name => name,
- :ensure => version
- }
+ begin
+ list = execute(command).split("\n").collect do |set|
+ if gemhash = gemsplit(set)
+ gemhash[:provider] = :gem
+ gemhash
else
- Puppet.warning "Could not match #{desc}"
- nil
+ nil
end
+ end.compact
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error, "Could not list gems: #{detail}"
end
- def self.instances(justme = false)
- gemlist(:local => true).collect do |hash|
- new(hash)
- end
+ if hash[:justme]
+ return list.shift
+ else
+ return list
end
+ end
+
+ def self.gemsplit(desc)
+ case desc
+ when /^\*\*\*/, /^\s*$/, /^\s+/; return nil
+ when /^(\S+)\s+\((.+)\)/
+ name = $1
+ version = $2.split(/,\s*/)[0]
+ return {
+ :name => name,
+ :ensure => version
+ }
+ else
+ Puppet.warning "Could not match #{desc}"
+ nil
+ end
+ end
- def install(useversion = true)
- command = [command(:gemcmd), "install"]
- command << "-v" << resource[:ensure] if (! resource[:ensure].is_a? Symbol) and useversion
- # Always include dependencies
- command << "--include-dependencies"
-
- if source = resource[:source]
- begin
- uri = URI.parse(source)
- rescue => detail
- fail "Invalid source '#{uri}': #{detail}"
- end
-
- case uri.scheme
- when nil
- # no URI scheme => interpret the source as a local file
- command << source
- when /file/i
- command << uri.path
- when 'puppet'
- # we don't support puppet:// URLs (yet)
- raise Puppet::Error.new("puppet:// URLs are not supported as gem sources")
- else
- # interpret it as a gem repository
- command << "--source" << "#{source}" << resource[:name]
- end
- else
- command << resource[:name]
- end
-
- output = execute(command)
- # Apparently some stupid gem versions don't exit non-0 on failure
- self.fail "Could not install: #{output.chomp}" if output.include?("ERROR")
+ def self.instances(justme = false)
+ gemlist(:local => true).collect do |hash|
+ new(hash)
+ end
+ end
+
+ def install(useversion = true)
+ command = [command(:gemcmd), "install"]
+ command << "-v" << resource[:ensure] if (! resource[:ensure].is_a? Symbol) and useversion
+ # Always include dependencies
+ command << "--include-dependencies"
+
+ if source = resource[:source]
+ begin
+ uri = URI.parse(source)
+ rescue => detail
+ fail "Invalid source '#{uri}': #{detail}"
+ end
+
+ case uri.scheme
+ when nil
+ # no URI scheme => interpret the source as a local file
+ command << source
+ when /file/i
+ command << uri.path
+ when 'puppet'
+ # we don't support puppet:// URLs (yet)
+ raise Puppet::Error.new("puppet:// URLs are not supported as gem sources")
+ else
+ # interpret it as a gem repository
+ command << "--source" << "#{source}" << resource[:name]
+ end
+ else
+ command << resource[:name]
end
- def latest
- # This always gets the latest version available.
- hash = self.class.gemlist(:justme => resource[:name])
+ output = execute(command)
+ # Apparently some stupid gem versions don't exit non-0 on failure
+ self.fail "Could not install: #{output.chomp}" if output.include?("ERROR")
+ end
- hash[:ensure]
- end
+ def latest
+ # This always gets the latest version available.
+ hash = self.class.gemlist(:justme => resource[:name])
- def query
- self.class.gemlist(:justme => resource[:name], :local => true)
- end
+ hash[:ensure]
+ end
- def uninstall
- gemcmd "uninstall", "-x", "-a", resource[:name]
- end
+ def query
+ self.class.gemlist(:justme => resource[:name], :local => true)
+ end
- def update
- self.install(false)
- end
+ def uninstall
+ gemcmd "uninstall", "-x", "-a", resource[:name]
+ end
+
+ def update
+ self.install(false)
+ end
end
diff --git a/lib/puppet/provider/package/hpux.rb b/lib/puppet/provider/package/hpux.rb
index 4d5394643..8396edf6d 100644
--- a/lib/puppet/provider/package/hpux.rb
+++ b/lib/puppet/provider/package/hpux.rb
@@ -4,41 +4,41 @@ require 'puppet/provider/package'
Puppet::Type.type(:package).provide :hpux, :parent => Puppet::Provider::Package do
- desc "HP-UX's packaging system."
-
- commands :swinstall => "/usr/sbin/swinstall",
- :swlist => "/usr/sbin/swlist",
- :swremove => "/usr/sbin/swremove"
-
- confine :operatingsystem => "hp-ux"
-
- defaultfor :operatingsystem => "hp-ux"
-
- def self.instances
- # TODO: This is very hard on HP-UX!
- []
- end
-
- # source and name are required
- def install
- raise ArgumentError, "source must be provided to install HP-UX packages" unless resource[:source]
- args = standard_args + ["-s", resource[:source], resource[:name]]
- swinstall(*args)
- end
-
- def query
- swlist resource[:name]
- {:ensure => :present}
- rescue
- {:ensure => :absent}
- end
-
- def uninstall
- args = standard_args + [resource[:name]]
- swremove(*args)
- end
-
- def standard_args
- ["-x", "mount_all_filesystems=false"]
- end
+ desc "HP-UX's packaging system."
+
+ commands :swinstall => "/usr/sbin/swinstall",
+ :swlist => "/usr/sbin/swlist",
+ :swremove => "/usr/sbin/swremove"
+
+ confine :operatingsystem => "hp-ux"
+
+ defaultfor :operatingsystem => "hp-ux"
+
+ def self.instances
+ # TODO: This is very hard on HP-UX!
+ []
+ end
+
+ # source and name are required
+ def install
+ raise ArgumentError, "source must be provided to install HP-UX packages" unless resource[:source]
+ args = standard_args + ["-s", resource[:source], resource[:name]]
+ swinstall(*args)
+ end
+
+ def query
+ swlist resource[:name]
+ {:ensure => :present}
+ rescue
+ {:ensure => :absent}
+ end
+
+ def uninstall
+ args = standard_args + [resource[:name]]
+ swremove(*args)
+ end
+
+ def standard_args
+ ["-x", "mount_all_filesystems=false"]
+ end
end
diff --git a/lib/puppet/provider/package/nim.rb b/lib/puppet/provider/package/nim.rb
index 33d4bf11d..8f52016db 100644
--- a/lib/puppet/provider/package/nim.rb
+++ b/lib/puppet/provider/package/nim.rb
@@ -2,34 +2,34 @@ require 'puppet/provider/package'
require 'puppet/util/package'
Puppet::Type.type(:package).provide :nim, :parent => :aix, :source => :aix do
- desc "Installation from NIM LPP source"
+ desc "Installation from NIM LPP source"
- # The commands we are using on an AIX box are installed standard
- # (except nimclient) nimclient needs the bos.sysmgt.nim.client fileset.
- commands :nimclient => "/usr/sbin/nimclient"
+ # The commands we are using on an AIX box are installed standard
+ # (except nimclient) nimclient needs the bos.sysmgt.nim.client fileset.
+ commands :nimclient => "/usr/sbin/nimclient"
- # If NIM has not been configured, /etc/niminfo will not be present.
- # However, we have no way of knowing if the NIM server is not configured
- # properly.
- confine :exists => "/etc/niminfo"
+ # If NIM has not been configured, /etc/niminfo will not be present.
+ # However, we have no way of knowing if the NIM server is not configured
+ # properly.
+ confine :exists => "/etc/niminfo"
- has_feature :versionable
+ has_feature :versionable
- attr_accessor :latest_info
+ attr_accessor :latest_info
- def self.srclistcmd(source)
- [ command(:nimclient), "-o", "showres", "-a", "installp_flags=L", "-a", "resource=#{source}" ]
- end
+ def self.srclistcmd(source)
+ [ command(:nimclient), "-o", "showres", "-a", "installp_flags=L", "-a", "resource=#{source}" ]
+ end
- def install(useversion = true)
- unless source = @resource[:source]
- self.fail "An LPP source location is required in 'source'"
- end
+ def install(useversion = true)
+ unless source = @resource[:source]
+ self.fail "An LPP source location is required in 'source'"
+ end
- pkg = @resource[:name]
+ pkg = @resource[:name]
- pkg << " " << @resource.should(:ensure) if (! @resource.should(:ensure).is_a? Symbol) and useversion
+ pkg << " " << @resource.should(:ensure) if (! @resource.should(:ensure).is_a? Symbol) and useversion
- nimclient "-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=#{source}", "-a", "filesets='#{pkg}'"
- end
+ nimclient "-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=#{source}", "-a", "filesets='#{pkg}'"
+ end
end
diff --git a/lib/puppet/provider/package/openbsd.rb b/lib/puppet/provider/package/openbsd.rb
index f6005efa7..ca477e56a 100755
--- a/lib/puppet/provider/package/openbsd.rb
+++ b/lib/puppet/provider/package/openbsd.rb
@@ -2,119 +2,119 @@ require 'puppet/provider/package'
# Packaging on OpenBSD. Doesn't work anywhere else that I know of.
Puppet::Type.type(:package).provide :openbsd, :parent => Puppet::Provider::Package do
- include Puppet::Util::Execution
- desc "OpenBSD's form of ``pkg_add`` support."
-
- commands :pkginfo => "pkg_info", :pkgadd => "pkg_add", :pkgdelete => "pkg_delete"
-
- defaultfor :operatingsystem => :openbsd
- confine :operatingsystem => :openbsd
-
- has_feature :versionable
-
- def self.instances
- packages = []
-
- begin
- execpipe(listcmd) do |process|
- # our regex for matching pkg_info output
- regex = /^(.*)-(\d[^-]*)[-]?(\D*)(.*)$/
- fields = [:name, :ensure, :flavor ]
- hash = {}
-
- # now turn each returned line into a package object
- process.each { |line|
- if match = regex.match(line.split[0])
- fields.zip(match.captures) { |field,value|
- hash[field] = value
- }
- yup = nil
- name = hash[:name]
-
- hash[:provider] = self.name
-
- packages << new(hash)
- hash = {}
- else
- # Print a warning on lines we can't match, but move
- # on, since it should be non-fatal
- warning("Failed to match line #{line}")
- end
- }
- end
-
- return packages
- rescue Puppet::ExecutionFailure
- return nil
- end
- end
+ include Puppet::Util::Execution
+ desc "OpenBSD's form of ``pkg_add`` support."
- def self.listcmd
- [command(:pkginfo), " -a"]
- end
+ commands :pkginfo => "pkg_info", :pkgadd => "pkg_add", :pkgdelete => "pkg_delete"
- def install
- should = @resource.should(:ensure)
+ defaultfor :operatingsystem => :openbsd
+ confine :operatingsystem => :openbsd
- unless @resource[:source]
- raise Puppet::Error,
- "You must specify a package source for BSD packages"
- end
+ has_feature :versionable
- old_ensure = @resource[:ensure]
+ def self.instances
+ packages = []
- if @resource[:source] =~ /\/$/
- withenv :PKG_PATH => @resource[:source] do
- @resource[:ensure] = old_ensure if (@resource[:ensure] = get_version) == nil
- full_name = [ @resource[:name], @resource[:ensure], @resource[:flavor] ]
- pkgadd full_name.join('-').chomp('-')
- end
- else
- pkgadd @resource[:source]
- end
+ begin
+ execpipe(listcmd) do |process|
+ # our regex for matching pkg_info output
+ regex = /^(.*)-(\d[^-]*)[-]?(\D*)(.*)$/
+ fields = [:name, :ensure, :flavor ]
+ hash = {}
+ # now turn each returned line into a package object
+ process.each { |line|
+ if match = regex.match(line.split[0])
+ fields.zip(match.captures) { |field,value|
+ hash[field] = value
+ }
+ yup = nil
+ name = hash[:name]
+
+ hash[:provider] = self.name
+
+ packages << new(hash)
+ hash = {}
+ else
+ # Print a warning on lines we can't match, but move
+ # on, since it should be non-fatal
+ warning("Failed to match line #{line}")
+ end
+ }
+ end
+
+ return packages
+ rescue Puppet::ExecutionFailure
+ return nil
end
+ end
- def get_version
- execpipe([command(:pkginfo), " -I ", @resource[:name]]) do |process|
- # our regex for matching pkg_info output
- regex = /^(.*)-(\d[^-]*)[-]?(\D*)(.*)$/
- fields = [ :name, :version, :flavor ]
- master_version = 0
-
- process.each do |line|
- if match = regex.match(line.split[0])
- # now we return the first version, unless ensure is latest
- version = match.captures[1]
- return version unless @resource[:ensure] == "latest"
-
- master_version = version unless master_version > version
- end
- end
-
- return master_version unless master_version == 0
- raise Puppet::Error, "#{version} is not available for this package"
- end
- rescue Puppet::ExecutionFailure
- return nil
+ def self.listcmd
+ [command(:pkginfo), " -a"]
+ end
+
+ def install
+ should = @resource.should(:ensure)
+
+ unless @resource[:source]
+ raise Puppet::Error,
+ "You must specify a package source for BSD packages"
end
- def query
- hash = {}
- info = pkginfo @resource[:name]
+ old_ensure = @resource[:ensure]
+
+ if @resource[:source] =~ /\/$/
+ withenv :PKG_PATH => @resource[:source] do
+ @resource[:ensure] = old_ensure if (@resource[:ensure] = get_version) == nil
+ full_name = [ @resource[:name], @resource[:ensure], @resource[:flavor] ]
+ pkgadd full_name.join('-').chomp('-')
+ end
+ else
+ pkgadd @resource[:source]
+ end
+
+ end
- # Search for the version info
- if info =~ /Information for (inst:)?#{@resource[:name]}-(\S+)/
- hash[:ensure] = $2
- else
- return nil
+ def get_version
+ execpipe([command(:pkginfo), " -I ", @resource[:name]]) do |process|
+ # our regex for matching pkg_info output
+ regex = /^(.*)-(\d[^-]*)[-]?(\D*)(.*)$/
+ fields = [ :name, :version, :flavor ]
+ master_version = 0
+
+ process.each do |line|
+ if match = regex.match(line.split[0])
+ # now we return the first version, unless ensure is latest
+ version = match.captures[1]
+ return version unless @resource[:ensure] == "latest"
+
+ master_version = version unless master_version > version
+ end
end
- hash
+ return master_version unless master_version == 0
+ raise Puppet::Error, "#{version} is not available for this package"
+ end
+ rescue Puppet::ExecutionFailure
+ return nil
+ end
+
+ def query
+ hash = {}
+ info = pkginfo @resource[:name]
+
+ # Search for the version info
+ if info =~ /Information for (inst:)?#{@resource[:name]}-(\S+)/
+ hash[:ensure] = $2
+ else
+ return nil
end
- def uninstall
- pkgdelete @resource[:name]
- end
+ hash
+ end
+
+ def uninstall
+ pkgdelete @resource[:name]
+ end
end
diff --git a/lib/puppet/provider/package/pkg.rb b/lib/puppet/provider/package/pkg.rb
index 35a712100..9a3733c95 100644
--- a/lib/puppet/provider/package/pkg.rb
+++ b/lib/puppet/provider/package/pkg.rb
@@ -1,108 +1,108 @@
require 'puppet/provider/package'
Puppet::Type.type(:package).provide :pkg, :parent => Puppet::Provider::Package do
- desc "OpenSolaris image packaging system. See pkg(5) for more information"
+ desc "OpenSolaris image packaging system. See pkg(5) for more information"
- commands :pkg => "/usr/bin/pkg"
+ commands :pkg => "/usr/bin/pkg"
- confine :operatingsystem => :solaris
+ confine :operatingsystem => :solaris
- #defaultfor [:operatingsystem => :solaris, :kernelrelease => "5.11"]
+ #defaultfor [:operatingsystem => :solaris, :kernelrelease => "5.11"]
- def self.instances
- packages = []
+ def self.instances
+ packages = []
- cmd = "#{command(:pkg)} list -H"
- execpipe(cmd) do |process|
- hash = {}
+ cmd = "#{command(:pkg)} list -H"
+ execpipe(cmd) do |process|
+ hash = {}
- # now turn each returned line into a package object
- process.each { |line|
- if hash = parse_line(line)
- packages << new(hash)
- end
- }
+ # now turn each returned line into a package object
+ process.each { |line|
+ if hash = parse_line(line)
+ packages << new(hash)
end
-
- packages
+ }
end
- self::REGEX = %r{^(\S+)\s+(\S+)\s+(\S+)\s+}
- self::FIELDS = [:name, :version, :status]
+ packages
+ end
- def self.parse_line(line)
- hash = {}
- if match = self::REGEX.match(line)
+ self::REGEX = %r{^(\S+)\s+(\S+)\s+(\S+)\s+}
+ self::FIELDS = [:name, :version, :status]
- self::FIELDS.zip(match.captures) { |field,value|
- hash[field] = value
- }
+ def self.parse_line(line)
+ hash = {}
+ if match = self::REGEX.match(line)
- hash[:provider] = self.name
- hash[:error] = "ok"
+ self::FIELDS.zip(match.captures) { |field,value|
+ hash[field] = value
+ }
- if hash[:status] == "installed"
- hash[:ensure] = :present
- else
- hash[:ensure] = :absent
- end
- else
- Puppet.warning "Failed to match 'pkg list' line #{line.inspect}"
- return nil
- end
+ hash[:provider] = self.name
+ hash[:error] = "ok"
- hash
+ if hash[:status] == "installed"
+ hash[:ensure] = :present
+ else
+ hash[:ensure] = :absent
+ end
+ else
+ Puppet.warning "Failed to match 'pkg list' line #{line.inspect}"
+ return nil
end
- # return the version of the package
- # TODO deal with multiple publishers
- def latest
- version = nil
- pkg(:list, "-Ha", @resource[:name]).split("\n").each do |line|
- v = line.split[2]
- case v
- when "known"
- return v
- when "installed"
- version = v
- else
- Puppet.warn "unknown package state for #{@resource[:name]}: #{v}"
- end
- end
- version
+ hash
+ end
+
+ # return the version of the package
+ # TODO deal with multiple publishers
+ def latest
+ version = nil
+ pkg(:list, "-Ha", @resource[:name]).split("\n").each do |line|
+ v = line.split[2]
+ case v
+ when "known"
+ return v
+ when "installed"
+ version = v
+ else
+ Puppet.warn "unknown package state for #{@resource[:name]}: #{v}"
+ end
end
-
- # install the package
- def install
- pkg :install, @resource[:name]
+ version
+ end
+
+ # install the package
+ def install
+ pkg :install, @resource[:name]
+ end
+
+ # uninstall the package
+ def uninstall
+ pkg :uninstall, '-r', @resource[:name]
+ end
+
+ # update the package to the latest version available
+ def update
+ self.install
+ end
+
+ # list a specific package
+ def query
+ begin
+ output = pkg(:list, "-H", @resource[:name])
+ rescue Puppet::ExecutionFailure
+ # pkg returns 1 if the package is not found.
+ return {:ensure => :absent, :status => 'missing',
+ :name => @resource[:name], :error => 'ok'}
end
- # uninstall the package
- def uninstall
- pkg :uninstall, '-r', @resource[:name]
- end
+ hash = self.class.parse_line(output) ||
+ {:ensure => :absent, :status => 'missing', :name => @resource[:name], :error => 'ok'}
- # update the package to the latest version available
- def update
- self.install
- end
+ raise Puppet::Error.new( "Package #{hash[:name]}, version #{hash[:version]} is in error state: #{hash[:error]}") if hash[:error] != "ok"
- # list a specific package
- def query
- begin
- output = pkg(:list, "-H", @resource[:name])
- rescue Puppet::ExecutionFailure
- # pkg returns 1 if the package is not found.
- return {:ensure => :absent, :status => 'missing',
- :name => @resource[:name], :error => 'ok'}
- end
-
- hash = self.class.parse_line(output) ||
- {:ensure => :absent, :status => 'missing', :name => @resource[:name], :error => 'ok'}
-
- raise Puppet::Error.new( "Package #{hash[:name]}, version #{hash[:version]} is in error state: #{hash[:error]}") if hash[:error] != "ok"
-
- hash
- end
+ hash
+ end
end
diff --git a/lib/puppet/provider/package/pkgdmg.rb b/lib/puppet/provider/package/pkgdmg.rb
index b533f1002..4506fbf9d 100644
--- a/lib/puppet/provider/package/pkgdmg.rb
+++ b/lib/puppet/provider/package/pkgdmg.rb
@@ -29,116 +29,116 @@ require 'puppet/provider/package'
require 'facter/util/plist'
Puppet::Type.type(:package).provide :pkgdmg, :parent => Puppet::Provider::Package do
- desc "Package management based on Apple's Installer.app and DiskUtility.app. This package works by checking the contents of a DMG image for Apple pkg or mpkg files. Any number of pkg or mpkg files may exist in the root directory of the DMG file system. Sub directories are not checked for packages. See `the wiki docs </trac/puppet/wiki/DmgPackages>` for more detail."
+ desc "Package management based on Apple's Installer.app and DiskUtility.app. This package works by checking the contents of a DMG image for Apple pkg or mpkg files. Any number of pkg or mpkg files may exist in the root directory of the DMG file system. Sub directories are not checked for packages. See `the wiki docs </trac/puppet/wiki/DmgPackages>` for more detail."
- confine :operatingsystem => :darwin
- defaultfor :operatingsystem => :darwin
- commands :installer => "/usr/sbin/installer"
- commands :hdiutil => "/usr/bin/hdiutil"
- commands :curl => "/usr/bin/curl"
+ confine :operatingsystem => :darwin
+ defaultfor :operatingsystem => :darwin
+ commands :installer => "/usr/sbin/installer"
+ commands :hdiutil => "/usr/bin/hdiutil"
+ commands :curl => "/usr/bin/curl"
- # JJM We store a cookie for each installed .pkg.dmg in /var/db
- def self.instance_by_name
- Dir.entries("/var/db").find_all { |f|
- f =~ /^\.puppet_pkgdmg_installed_/
- }.collect do |f|
- name = f.sub(/^\.puppet_pkgdmg_installed_/, '')
- yield name if block_given?
- name
- end
+ # JJM We store a cookie for each installed .pkg.dmg in /var/db
+ def self.instance_by_name
+ Dir.entries("/var/db").find_all { |f|
+ f =~ /^\.puppet_pkgdmg_installed_/
+ }.collect do |f|
+ name = f.sub(/^\.puppet_pkgdmg_installed_/, '')
+ yield name if block_given?
+ name
end
+ end
- def self.instances
- instance_by_name.collect do |name|
+ def self.instances
+ instance_by_name.collect do |name|
- new(
+ new(
- :name => name,
- :provider => :pkgdmg,
+ :name => name,
+ :provider => :pkgdmg,
- :ensure => :installed
- )
- end
+ :ensure => :installed
+ )
end
+ end
- def self.installpkg(source, name, orig_source)
- installer "-pkg", source, "-target", "/"
- # Non-zero exit status will throw an exception.
- File.open("/var/db/.puppet_pkgdmg_installed_#{name}", "w") do |t|
- t.print "name: '#{name}'\n"
- t.print "source: '#{orig_source}'\n"
- end
+ def self.installpkg(source, name, orig_source)
+ installer "-pkg", source, "-target", "/"
+ # Non-zero exit status will throw an exception.
+ File.open("/var/db/.puppet_pkgdmg_installed_#{name}", "w") do |t|
+ t.print "name: '#{name}'\n"
+ t.print "source: '#{orig_source}'\n"
end
+ end
- def self.installpkgdmg(source, name)
- unless source =~ /\.dmg$/i || source =~ /\.pkg$/i
- raise Puppet::Error.new("Mac OS X PKG DMG's must specificy a source string ending in .dmg or flat .pkg file")
- end
- require 'open-uri'
+ def self.installpkgdmg(source, name)
+ unless source =~ /\.dmg$/i || source =~ /\.pkg$/i
+ raise Puppet::Error.new("Mac OS X PKG DMG's must specificy a source string ending in .dmg or flat .pkg file")
+ end
+ require 'open-uri'
+ cached_source = source
+ if %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ cached_source
+ cached_source = "/tmp/#{name}"
+ begin
+ curl "-o", cached_source, "-C", "-", "-k", "-s", "--url", source
+ Puppet.debug "Success: curl transfered [#{name}]"
+ rescue Puppet::ExecutionFailure
+ Puppet.debug "curl did not transfer [#{name}]. Falling back to slower open-uri transfer methods."
cached_source = source
- if %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ cached_source
- cached_source = "/tmp/#{name}"
- begin
- curl "-o", cached_source, "-C", "-", "-k", "-s", "--url", source
- Puppet.debug "Success: curl transfered [#{name}]"
- rescue Puppet::ExecutionFailure
- Puppet.debug "curl did not transfer [#{name}]. Falling back to slower open-uri transfer methods."
- cached_source = source
- end
- end
+ end
+ end
- begin
- if source =~ /\.dmg$/i
- File.open(cached_source) do |dmg|
- xml_str = hdiutil "mount", "-plist", "-nobrowse", "-readonly", "-noidme", "-mountrandom", "/tmp", dmg.path
- hdiutil_info = Plist::parse_xml(xml_str)
- raise Puppet::Error.new("No disk entities returned by mount at #{dmg.path}") unless hdiutil_info.has_key?("system-entities")
- mounts = hdiutil_info["system-entities"].collect { |entity|
- entity["mount-point"]
- }.compact
- begin
- mounts.each do |mountpoint|
- Dir.entries(mountpoint).select { |f|
- f =~ /\.m{0,1}pkg$/i
- }.each do |pkg|
- installpkg("#{mountpoint}/#{pkg}", name, source)
- end
- end
- ensure
- mounts.each do |mountpoint|
- hdiutil "eject", mountpoint
- end
- end
- end
- elsif source =~ /\.pkg$/i
- installpkg(cached_source, name, source)
- else
- raise Puppet::Error.new("Mac OS X PKG DMG's must specificy a source string ending in .dmg or flat .pkg file")
+ begin
+ if source =~ /\.dmg$/i
+ File.open(cached_source) do |dmg|
+ xml_str = hdiutil "mount", "-plist", "-nobrowse", "-readonly", "-noidme", "-mountrandom", "/tmp", dmg.path
+ hdiutil_info = Plist::parse_xml(xml_str)
+ raise Puppet::Error.new("No disk entities returned by mount at #{dmg.path}") unless hdiutil_info.has_key?("system-entities")
+ mounts = hdiutil_info["system-entities"].collect { |entity|
+ entity["mount-point"]
+ }.compact
+ begin
+ mounts.each do |mountpoint|
+ Dir.entries(mountpoint).select { |f|
+ f =~ /\.m{0,1}pkg$/i
+ }.each do |pkg|
+ installpkg("#{mountpoint}/#{pkg}", name, source)
+ end
+ end
+ ensure
+ mounts.each do |mountpoint|
+ hdiutil "eject", mountpoint
end
- ensure
- # JJM Remove the file if open-uri didn't already do so.
- File.unlink(cached_source) if File.exist?(cached_source)
+ end
end
+ elsif source =~ /\.pkg$/i
+ installpkg(cached_source, name, source)
+ else
+ raise Puppet::Error.new("Mac OS X PKG DMG's must specificy a source string ending in .dmg or flat .pkg file")
+ end
+ ensure
+ # JJM Remove the file if open-uri didn't already do so.
+ File.unlink(cached_source) if File.exist?(cached_source)
end
+ end
- def query
- if FileTest.exists?("/var/db/.puppet_pkgdmg_installed_#{@resource[:name]}")
- Puppet.debug "/var/db/.puppet_pkgdmg_installed_#{@resource[:name]} found"
- return {:name => @resource[:name], :ensure => :present}
- else
- return nil
- end
+ def query
+ if FileTest.exists?("/var/db/.puppet_pkgdmg_installed_#{@resource[:name]}")
+ Puppet.debug "/var/db/.puppet_pkgdmg_installed_#{@resource[:name]} found"
+ return {:name => @resource[:name], :ensure => :present}
+ else
+ return nil
end
+ end
- def install
- source = nil
- unless source = @resource[:source]
- raise Puppet::Error.new("Mac OS X PKG DMG's must specify a package source.")
- end
- unless name = @resource[:name]
- raise Puppet::Error.new("Mac OS X PKG DMG's must specify a package name.")
- end
- self.class.installpkgdmg(source,name)
+ def install
+ source = nil
+ unless source = @resource[:source]
+ raise Puppet::Error.new("Mac OS X PKG DMG's must specify a package source.")
+ end
+ unless name = @resource[:name]
+ raise Puppet::Error.new("Mac OS X PKG DMG's must specify a package name.")
end
+ self.class.installpkgdmg(source,name)
+ end
end
diff --git a/lib/puppet/provider/package/portage.rb b/lib/puppet/provider/package/portage.rb
index 82d16699c..30f0e4a25 100644
--- a/lib/puppet/provider/package/portage.rb
+++ b/lib/puppet/provider/package/portage.rb
@@ -2,121 +2,121 @@ require 'puppet/provider/package'
require 'fileutils'
Puppet::Type.type(:package).provide :portage, :parent => Puppet::Provider::Package do
- desc "Provides packaging support for Gentoo's portage system."
+ desc "Provides packaging support for Gentoo's portage system."
- has_feature :versionable
+ has_feature :versionable
- commands :emerge => "/usr/bin/emerge", :eix => "/usr/bin/eix", :update_eix => "/usr/bin/eix-update"
+ commands :emerge => "/usr/bin/emerge", :eix => "/usr/bin/eix", :update_eix => "/usr/bin/eix-update"
- confine :operatingsystem => :gentoo
+ confine :operatingsystem => :gentoo
- defaultfor :operatingsystem => :gentoo
+ defaultfor :operatingsystem => :gentoo
- def self.instances
- result_format = /^(\S+)\s+(\S+)\s+\[(\S+)\]\s+\[(\S+)\]\s+(\S+)\s+(.*)$/
- result_fields = [:category, :name, :ensure, :version_available, :vendor, :description]
+ def self.instances
+ result_format = /^(\S+)\s+(\S+)\s+\[(\S+)\]\s+\[(\S+)\]\s+(\S+)\s+(.*)$/
+ result_fields = [:category, :name, :ensure, :version_available, :vendor, :description]
- version_format = "{last}<version>{}"
- search_format = "<category> <name> [<installedversions:LASTVERSION>] [<bestversion:LASTVERSION>] <homepage> <description>\n"
+ version_format = "{last}<version>{}"
+ search_format = "<category> <name> [<installedversions:LASTVERSION>] [<bestversion:LASTVERSION>] <homepage> <description>\n"
- begin
- update_eix if !FileUtils.uptodate?("/var/cache/eix", %w{/usr/bin/eix /usr/portage/metadata/timestamp})
+ begin
+ update_eix if !FileUtils.uptodate?("/var/cache/eix", %w{/usr/bin/eix /usr/portage/metadata/timestamp})
- search_output = nil
- Puppet::Util::Execution.withenv :LASTVERSION => version_format do
- search_output = eix "--nocolor", "--pure-packages", "--stable", "--installed", "--format", search_format
- end
+ search_output = nil
+ Puppet::Util::Execution.withenv :LASTVERSION => version_format do
+ search_output = eix "--nocolor", "--pure-packages", "--stable", "--installed", "--format", search_format
+ end
- packages = []
- search_output.each do |search_result|
- match = result_format.match(search_result)
+ packages = []
+ search_output.each do |search_result|
+ match = result_format.match(search_result)
- if match
- package = {}
- result_fields.zip(match.captures) do |field, value|
- package[field] = value unless !value or value.empty?
- end
- package[:provider] = :portage
- packages << new(package)
- end
- end
-
- return packages
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error.new(detail)
+ if match
+ package = {}
+ result_fields.zip(match.captures) do |field, value|
+ package[field] = value unless !value or value.empty?
+ end
+ package[:provider] = :portage
+ packages << new(package)
end
- end
-
- def install
- should = @resource.should(:ensure)
- name = package_name
- unless should == :present or should == :latest
- # We must install a specific version
- name = "=#{name}-#{should}"
- end
- emerge name
- end
+ end
- # The common package name format.
- def package_name
- @resource[:category] ? "#{@resource[:category]}/#{@resource[:name]}" : @resource[:name]
+ return packages
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error.new(detail)
end
-
- def uninstall
- emerge "--unmerge", package_name
- end
-
- def update
- self.install
+ end
+
+ def install
+ should = @resource.should(:ensure)
+ name = package_name
+ unless should == :present or should == :latest
+ # We must install a specific version
+ name = "=#{name}-#{should}"
end
-
- def query
- result_format = /^(\S+)\s+(\S+)\s+\[(\S*)\]\s+\[(\S+)\]\s+(\S+)\s+(.*)$/
- result_fields = [:category, :name, :ensure, :version_available, :vendor, :description]
-
- version_format = "{last}<version>{}"
- search_format = "<category> <name> [<installedversions:LASTVERSION>] [<bestversion:LASTVERSION>] <homepage> <description>\n"
-
- search_field = package_name.count('/') > 0 ? "--category-name" : "--name"
- search_value = package_name
-
- begin
- update_eix if !FileUtils.uptodate?("/var/cache/eix", %w{/usr/bin/eix /usr/portage/metadata/timestamp})
-
- search_output = nil
- Puppet::Util::Execution.withenv :LASTVERSION => version_format do
- search_output = eix "--nocolor", "--pure-packages", "--stable", "--format", search_format, "--exact", search_field, search_value
- end
-
- packages = []
- search_output.each do |search_result|
- match = result_format.match(search_result)
-
- if match
- package = {}
- result_fields.zip(match.captures) do |field, value|
- package[field] = value unless !value or value.empty?
- end
- package[:ensure] = package[:ensure] ? package[:ensure] : :absent
- packages << package
- end
- end
-
- case packages.size
- when 0
- not_found_value = "#{@resource[:category] ? @resource[:category] : "<unspecified category>"}/#{@resource[:name]}"
- raise Puppet::Error.new("No package found with the specified name [#{not_found_value}]")
- when 1
- return packages[0]
- else
- raise Puppet::Error.new("More than one package with the specified name [#{search_value}], please use the category parameter to disambiguate")
- end
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error.new(detail)
+ emerge name
+ end
+
+ # The common package name format.
+ def package_name
+ @resource[:category] ? "#{@resource[:category]}/#{@resource[:name]}" : @resource[:name]
+ end
+
+ def uninstall
+ emerge "--unmerge", package_name
+ end
+
+ def update
+ self.install
+ end
+
+ def query
+ result_format = /^(\S+)\s+(\S+)\s+\[(\S*)\]\s+\[(\S+)\]\s+(\S+)\s+(.*)$/
+ result_fields = [:category, :name, :ensure, :version_available, :vendor, :description]
+
+ version_format = "{last}<version>{}"
+ search_format = "<category> <name> [<installedversions:LASTVERSION>] [<bestversion:LASTVERSION>] <homepage> <description>\n"
+
+ search_field = package_name.count('/') > 0 ? "--category-name" : "--name"
+ search_value = package_name
+
+ begin
+ update_eix if !FileUtils.uptodate?("/var/cache/eix", %w{/usr/bin/eix /usr/portage/metadata/timestamp})
+
+ search_output = nil
+ Puppet::Util::Execution.withenv :LASTVERSION => version_format do
+ search_output = eix "--nocolor", "--pure-packages", "--stable", "--format", search_format, "--exact", search_field, search_value
+ end
+
+ packages = []
+ search_output.each do |search_result|
+ match = result_format.match(search_result)
+
+ if match
+ package = {}
+ result_fields.zip(match.captures) do |field, value|
+ package[field] = value unless !value or value.empty?
+ end
+ package[:ensure] = package[:ensure] ? package[:ensure] : :absent
+ packages << package
end
+ end
+
+ case packages.size
+ when 0
+ not_found_value = "#{@resource[:category] ? @resource[:category] : "<unspecified category>"}/#{@resource[:name]}"
+ raise Puppet::Error.new("No package found with the specified name [#{not_found_value}]")
+ when 1
+ return packages[0]
+ else
+ raise Puppet::Error.new("More than one package with the specified name [#{search_value}], please use the category parameter to disambiguate")
+ end
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error.new(detail)
end
+ end
- def latest
- self.query[:version_available]
- end
+ def latest
+ self.query[:version_available]
+ end
end
diff --git a/lib/puppet/provider/package/ports.rb b/lib/puppet/provider/package/ports.rb
index 1b8f0fb8c..c8020928e 100755
--- a/lib/puppet/provider/package/ports.rb
+++ b/lib/puppet/provider/package/ports.rb
@@ -1,95 +1,95 @@
Puppet::Type.type(:package).provide :ports, :parent => :freebsd, :source => :freebsd do
- desc "Support for FreeBSD's ports. Again, this still mixes packages and ports."
+ desc "Support for FreeBSD's ports. Again, this still mixes packages and ports."
- commands :portupgrade => "/usr/local/sbin/portupgrade",
- :portversion => "/usr/local/sbin/portversion",
- :portuninstall => "/usr/local/sbin/pkg_deinstall",
- :portinfo => "/usr/sbin/pkg_info"
+ commands :portupgrade => "/usr/local/sbin/portupgrade",
+ :portversion => "/usr/local/sbin/portversion",
+ :portuninstall => "/usr/local/sbin/pkg_deinstall",
+ :portinfo => "/usr/sbin/pkg_info"
- defaultfor :operatingsystem => :freebsd
+ defaultfor :operatingsystem => :freebsd
- # I hate ports
- %w{INTERACTIVE UNAME}.each do |var|
- ENV.delete(var) if ENV.include?(var)
- end
+ # I hate ports
+ %w{INTERACTIVE UNAME}.each do |var|
+ ENV.delete(var) if ENV.include?(var)
+ end
- def install
- # -N: install if the package is missing, otherwise upgrade
- # -M: yes, we're a batch, so don't ask any questions
- cmd = %w{-N -M BATCH=yes} << @resource[:name]
+ def install
+ # -N: install if the package is missing, otherwise upgrade
+ # -M: yes, we're a batch, so don't ask any questions
+ cmd = %w{-N -M BATCH=yes} << @resource[:name]
- output = portupgrade(*cmd)
- if output =~ /\*\* No such /
- raise Puppet::ExecutionFailure, "Could not find package #{@resource[:name]}"
- end
+ output = portupgrade(*cmd)
+ if output =~ /\*\* No such /
+ raise Puppet::ExecutionFailure, "Could not find package #{@resource[:name]}"
end
+ end
- # If there are multiple packages, we only use the last one
- def latest
- cmd = ["-v", @resource[:name]]
+ # If there are multiple packages, we only use the last one
+ def latest
+ cmd = ["-v", @resource[:name]]
- begin
- output = portversion(*cmd)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
- line = output.split("\n").pop
+ begin
+ output = portversion(*cmd)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ end
+ line = output.split("\n").pop
- unless line =~ /^(\S+)\s+(\S)\s+(.+)$/
- # There's no "latest" version, so just return a placeholder
- return :latest
- end
+ unless line =~ /^(\S+)\s+(\S)\s+(.+)$/
+ # There's no "latest" version, so just return a placeholder
+ return :latest
+ end
- pkgstuff = $1
- match = $2
- info = $3
+ pkgstuff = $1
+ match = $2
+ info = $3
- unless pkgstuff =~ /^(\S+)-([^-\s]+)$/
- raise Puppet::Error,
- "Could not match package info '#{pkgstuff}'"
- end
+ unless pkgstuff =~ /^(\S+)-([^-\s]+)$/
+ raise Puppet::Error,
+ "Could not match package info '#{pkgstuff}'"
+ end
- name, version = $1, $2
+ name, version = $1, $2
- if match == "=" or match == ">"
- # we're up to date or more recent
- return version
- end
+ if match == "=" or match == ">"
+ # we're up to date or more recent
+ return version
+ end
- # Else, we need to be updated; we need to pull out the new version
+ # Else, we need to be updated; we need to pull out the new version
- unless info =~ /\((\w+) has (.+)\)/
- raise Puppet::Error,
- "Could not match version info '#{info}'"
- end
+ unless info =~ /\((\w+) has (.+)\)/
+ raise Puppet::Error,
+ "Could not match version info '#{info}'"
+ end
- source, newversion = $1, $2
+ source, newversion = $1, $2
- debug "Newer version in #{source}"
- newversion
- end
+ debug "Newer version in #{source}"
+ newversion
+ end
- def query
- # support portorigin_glob such as "mail/postfix"
- name = self.name
- if name =~ /\//
- name = self.name.split(/\//).slice(1)
- end
- self.class.instances.each do |instance|
- if instance.name == name
- return instance.properties
- end
- end
-
- nil
+ def query
+ # support portorigin_glob such as "mail/postfix"
+ name = self.name
+ if name =~ /\//
+ name = self.name.split(/\//).slice(1)
end
-
- def uninstall
- portuninstall @resource[:name]
+ self.class.instances.each do |instance|
+ if instance.name == name
+ return instance.properties
+ end
end
- def update
- install
- end
+ nil
+ end
+
+ def uninstall
+ portuninstall @resource[:name]
+ end
+
+ def update
+ install
+ end
end
diff --git a/lib/puppet/provider/package/portupgrade.rb b/lib/puppet/provider/package/portupgrade.rb
index 08cb52f47..45e35bbca 100644
--- a/lib/puppet/provider/package/portupgrade.rb
+++ b/lib/puppet/provider/package/portupgrade.rb
@@ -3,248 +3,248 @@
require 'puppet/provider/package'
Puppet::Type.type(:package).provide :portupgrade, :parent => Puppet::Provider::Package do
- include Puppet::Util::Execution
+ include Puppet::Util::Execution
- desc "Support for FreeBSD's ports using the portupgrade ports management software.
- Use the port's full origin as the resource name. eg (ports-mgmt/portupgrade)
- for the portupgrade port."
+ desc "Support for FreeBSD's ports using the portupgrade ports management software.
+ Use the port's full origin as the resource name. eg (ports-mgmt/portupgrade)
+ for the portupgrade port."
- ## has_features is usually autodetected based on defs below.
- # has_features :installable, :uninstallable, :upgradeable
+ ## has_features is usually autodetected based on defs below.
+ # has_features :installable, :uninstallable, :upgradeable
- commands :portupgrade => "/usr/local/sbin/portupgrade",
- :portinstall => "/usr/local/sbin/portinstall",
- :portversion => "/usr/local/sbin/portversion",
- :portuninstall => "/usr/local/sbin/pkg_deinstall",
- :portinfo => "/usr/sbin/pkg_info"
+ commands :portupgrade => "/usr/local/sbin/portupgrade",
+ :portinstall => "/usr/local/sbin/portinstall",
+ :portversion => "/usr/local/sbin/portversion",
+ :portuninstall => "/usr/local/sbin/pkg_deinstall",
+ :portinfo => "/usr/sbin/pkg_info"
- ## Activate this only once approved by someone important.
- # defaultfor :operatingsystem => :freebsd
+ ## Activate this only once approved by someone important.
+ # defaultfor :operatingsystem => :freebsd
- # Remove unwanted environment variables.
- %w{INTERACTIVE UNAME}.each do |var|
- if ENV.include?(var)
- ENV.delete(var)
- end
- end
-
- ######## instances sub command (builds the installed packages list)
-
- def self.instances
- Puppet.debug "portupgrade.rb Building packages list from installed ports"
-
- # regex to match output from pkg_info
- regex = %r{^(\S+)-([^-\s]+):(\S+)$}
- # Corresponding field names
- fields = [:portname, :ensure, :portorigin]
- # define Temporary hash used, packages array of hashes
- hash = Hash.new
- packages = []
-
- # exec command
- cmdline = ["-aoQ"]
- begin
- output = portinfo(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- return nil
- end
+ # Remove unwanted environment variables.
+ %w{INTERACTIVE UNAME}.each do |var|
+ if ENV.include?(var)
+ ENV.delete(var)
+ end
+ end
+
+ ######## instances sub command (builds the installed packages list)
+
+ def self.instances
+ Puppet.debug "portupgrade.rb Building packages list from installed ports"
+
+ # regex to match output from pkg_info
+ regex = %r{^(\S+)-([^-\s]+):(\S+)$}
+ # Corresponding field names
+ fields = [:portname, :ensure, :portorigin]
+ # define Temporary hash used, packages array of hashes
+ hash = Hash.new
+ packages = []
+
+ # exec command
+ cmdline = ["-aoQ"]
+ begin
+ output = portinfo(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ return nil
+ end
- # split output and match it and populate temp hash
- output.split("\n").each { |data|
- # reset hash to nil for each line
- hash.clear
- if match = regex.match(data)
- # Output matched regex
- fields.zip(match.captures) { |field, value|
- hash[field] = value
- }
-
- # populate the actual :name field from the :portorigin
- # Set :provider to this object name
- hash[:name] = hash[:portorigin]
- hash[:provider] = self.name
-
- # Add to the full packages listing
- packages << new(hash)
-
- else
- # unrecognised output from pkg_info
- Puppet.debug "portupgrade.Instances() - unable to match output: #{data}"
- end
- }
-
- # return the packages array of hashes
- return packages
+ # split output and match it and populate temp hash
+ output.split("\n").each { |data|
+ # reset hash to nil for each line
+ hash.clear
+ if match = regex.match(data)
+ # Output matched regex
+ fields.zip(match.captures) { |field, value|
+ hash[field] = value
+ }
+
+ # populate the actual :name field from the :portorigin
+ # Set :provider to this object name
+ hash[:name] = hash[:portorigin]
+ hash[:provider] = self.name
+
+ # Add to the full packages listing
+ packages << new(hash)
+
+ else
+ # unrecognised output from pkg_info
+ Puppet.debug "portupgrade.Instances() - unable to match output: #{data}"
+ end
+ }
- end
+ # return the packages array of hashes
+ return packages
- ######## Installation sub command
+ end
- def install
- Puppet.debug "portupgrade.install() - Installation call on #{@resource[:name]}"
- # -M: yes, we're a batch, so don't ask any questions
- cmdline = ["-M BATCH=yes", @resource[:name]]
+ ######## Installation sub command
- # FIXME: it's possible that portinstall prompts for data so locks up.
- begin
- output = portinstall(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
+ def install
+ Puppet.debug "portupgrade.install() - Installation call on #{@resource[:name]}"
+ # -M: yes, we're a batch, so don't ask any questions
+ cmdline = ["-M BATCH=yes", @resource[:name]]
- if output =~ /\*\* No such /
- raise Puppet::ExecutionFailure, "Could not find package #{@resource[:name]}"
- end
+ # FIXME: it's possible that portinstall prompts for data so locks up.
+ begin
+ output = portinstall(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ end
- # No return code required, so do nil to be clean
- return nil
+ if output =~ /\*\* No such /
+ raise Puppet::ExecutionFailure, "Could not find package #{@resource[:name]}"
end
- ######## Latest subcommand (returns the latest version available, or current version if installed is latest)
+ # No return code required, so do nil to be clean
+ return nil
+ end
- def latest
- Puppet.debug "portupgrade.latest() - Latest check called on #{@resource[:name]}"
- # search for latest version available, or return current version.
- # cmdline = "portversion -v <portorigin>", returns "<portname> <code> <stuff>"
- # or "** No matching package found: <portname>"
- cmdline = ["-v", @resource[:name]]
+ ######## Latest subcommand (returns the latest version available, or current version if installed is latest)
- begin
- output = portversion(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
+ def latest
+ Puppet.debug "portupgrade.latest() - Latest check called on #{@resource[:name]}"
+ # search for latest version available, or return current version.
+ # cmdline = "portversion -v <portorigin>", returns "<portname> <code> <stuff>"
+ # or "** No matching package found: <portname>"
+ cmdline = ["-v", @resource[:name]]
- # Check: output format.
- if output =~ /^\S+-([^-\s]+)\s+(\S)\s+(.*)/
- # $1 = installed version, $2 = comparison, $3 other data
- # latest installed
- installedversion = $1
- comparison = $2
- otherdata = $3
-
- # Only return a new version number when it's clear that there is a new version
- # all others return the current version so no unexpected 'upgrades' occur.
- case comparison
- when "=", ">"
- Puppet.debug "portupgrade.latest() - Installed package is latest (#{installedversion})"
- return installedversion
- when "<"
- # "portpkg-1.7_5 < needs updating (port has 1.14)"
- # "portpkg-1.7_5 < needs updating (port has 1.14) (=> 'newport/pkg')
- if otherdata =~ /\(port has (\S+)\)/
- newversion = $1
- Puppet.debug "portupgrade.latest() - Installed version needs updating to (#{newversion})"
- return newversion
- else
- Puppet.debug "portupgrade.latest() - Unable to determine new version from (#{otherdata})"
- return installedversion
- end
- when "?", "!", "#"
- Puppet.debug "portupgrade.latest() - Comparison Error reported from portversion (#{output})"
- return installedversion
- else
- Puppet.debug "portupgrade.latest() - Unknown code from portversion output (#{output})"
- return installedversion
- end
+ begin
+ output = portversion(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ end
+ # Check: output format.
+ if output =~ /^\S+-([^-\s]+)\s+(\S)\s+(.*)/
+ # $1 = installed version, $2 = comparison, $3 other data
+ # latest installed
+ installedversion = $1
+ comparison = $2
+ otherdata = $3
+
+ # Only return a new version number when it's clear that there is a new version
+ # all others return the current version so no unexpected 'upgrades' occur.
+ case comparison
+ when "=", ">"
+ Puppet.debug "portupgrade.latest() - Installed package is latest (#{installedversion})"
+ return installedversion
+ when "<"
+ # "portpkg-1.7_5 < needs updating (port has 1.14)"
+ # "portpkg-1.7_5 < needs updating (port has 1.14) (=> 'newport/pkg')
+ if otherdata =~ /\(port has (\S+)\)/
+ newversion = $1
+ Puppet.debug "portupgrade.latest() - Installed version needs updating to (#{newversion})"
+ return newversion
else
- # error: output not parsed correctly, error out with nil.
- # Seriously - this section should never be called in a perfect world.
- # as verification that the port is installed has already happened in query.
- if output =~ /^\*\* No matching package /
- raise Puppet::ExecutionFailure, "Could not find package #{@resource[:name]}"
- else
- # Any other error (dump output to log)
- raise Puppet::ExecutionFailure, "Unexpected output from portversion: #{output}"
- end
-
- # Just in case we still are running, return nil
- return nil
+ Puppet.debug "portupgrade.latest() - Unable to determine new version from (#{otherdata})"
+ return installedversion
end
+ when "?", "!", "#"
+ Puppet.debug "portupgrade.latest() - Comparison Error reported from portversion (#{output})"
+ return installedversion
+ else
+ Puppet.debug "portupgrade.latest() - Unknown code from portversion output (#{output})"
+ return installedversion
+ end
- # At this point normal operation has finished and we shouldn't have been called.
- # Error out and let the admin deal with it.
- raise Puppet::Error, "portversion.latest() - fatal error with portversion: #{output}"
- return nil
+ else
+ # error: output not parsed correctly, error out with nil.
+ # Seriously - this section should never be called in a perfect world.
+ # as verification that the port is installed has already happened in query.
+ if output =~ /^\*\* No matching package /
+ raise Puppet::ExecutionFailure, "Could not find package #{@resource[:name]}"
+ else
+ # Any other error (dump output to log)
+ raise Puppet::ExecutionFailure, "Unexpected output from portversion: #{output}"
+ end
+ # Just in case we still are running, return nil
+ return nil
end
- ###### Query subcommand - return a hash of details if exists, or nil if it doesn't.
- # Used to make sure the package is installed
+ # At this point normal operation has finished and we shouldn't have been called.
+ # Error out and let the admin deal with it.
+ raise Puppet::Error, "portversion.latest() - fatal error with portversion: #{output}"
+ return nil
- def query
- Puppet.debug "portupgrade.query() - Called on #{@resource[:name]}"
+ end
- cmdline = ["-qO", @resource[:name]]
- begin
- output = portinfo(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
+ ###### Query subcommand - return a hash of details if exists, or nil if it doesn't.
+ # Used to make sure the package is installed
- # Check: if output isn't in the right format, return nil
- if output =~ /^(\S+)-([^-\s]+)/
- # Fill in the details
- hash = Hash.new
- hash[:portorigin] = self.name
- hash[:portname] = $1
- hash[:ensure] = $2
-
- # If more details are required, then we can do another pkg_info query here
- # and parse out that output and add to the hash
-
- # return the hash to the caller
- return hash
- else
- Puppet.debug "portupgrade.query() - package (#{@resource[:name]}) not installed"
- return nil
- end
+ def query
+ Puppet.debug "portupgrade.query() - Called on #{@resource[:name]}"
+ cmdline = ["-qO", @resource[:name]]
+ begin
+ output = portinfo(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
end
- ####### Uninstall command
+ # Check: if output isn't in the right format, return nil
+ if output =~ /^(\S+)-([^-\s]+)/
+ # Fill in the details
+ hash = Hash.new
+ hash[:portorigin] = self.name
+ hash[:portname] = $1
+ hash[:ensure] = $2
+
+ # If more details are required, then we can do another pkg_info query here
+ # and parse out that output and add to the hash
+
+ # return the hash to the caller
+ return hash
+ else
+ Puppet.debug "portupgrade.query() - package (#{@resource[:name]}) not installed"
+ return nil
+ end
- def uninstall
- Puppet.debug "portupgrade.uninstall() - called on #{@resource[:name]}"
- # Get full package name from port origin to uninstall with
- cmdline = ["-qO", @resource[:name]]
- begin
- output = portinfo(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
+ end
- if output =~ /^(\S+)/
- # output matches, so uninstall it
- portuninstall $1
- end
+ ####### Uninstall command
+ def uninstall
+ Puppet.debug "portupgrade.uninstall() - called on #{@resource[:name]}"
+ # Get full package name from port origin to uninstall with
+ cmdline = ["-qO", @resource[:name]]
+ begin
+ output = portinfo(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
end
- ######## Update/upgrade command
+ if output =~ /^(\S+)/
+ # output matches, so uninstall it
+ portuninstall $1
+ end
- def update
- Puppet.debug "portupgrade.update() - called on (#{@resource[:name]})"
+ end
- cmdline = ["-qO", @resource[:name]]
- begin
- output = portinfo(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
+ ######## Update/upgrade command
- if output =~ /^(\S+)/
- # output matches, so upgrade the software
- cmdline = ["-M BATCH=yes", $1]
- begin
- output = portupgrade(*cmdline)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new(output)
- end
- end
+ def update
+ Puppet.debug "portupgrade.update() - called on (#{@resource[:name]})"
+
+ cmdline = ["-qO", @resource[:name]]
+ begin
+ output = portinfo(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ end
+
+ if output =~ /^(\S+)/
+ # output matches, so upgrade the software
+ cmdline = ["-M BATCH=yes", $1]
+ begin
+ output = portupgrade(*cmdline)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new(output)
+ end
end
+ end
## EOF
end
diff --git a/lib/puppet/provider/package/rpm.rb b/lib/puppet/provider/package/rpm.rb
index cabdd1b1f..d33a4f2f3 100755
--- a/lib/puppet/provider/package/rpm.rb
+++ b/lib/puppet/provider/package/rpm.rb
@@ -1,132 +1,132 @@
require 'puppet/provider/package'
# RPM packaging. Should work anywhere that has rpm installed.
Puppet::Type.type(:package).provide :rpm, :source => :rpm, :parent => Puppet::Provider::Package do
- desc "RPM packaging support; should work anywhere with a working ``rpm``
- binary."
-
- has_feature :versionable
-
- # The query format by which we identify installed packages
- NEVRAFORMAT = "%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}"
- NEVRA_FIELDS = [:name, :epoch, :version, :release, :arch]
-
- commands :rpm => "rpm"
-
- if command('rpm')
- confine :true => begin
- rpm('--version')
- rescue Puppet::ExecutionFailure
- false
- else
- true
- end
+ desc "RPM packaging support; should work anywhere with a working ``rpm``
+ binary."
+
+ has_feature :versionable
+
+ # The query format by which we identify installed packages
+ NEVRAFORMAT = "%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}"
+ NEVRA_FIELDS = [:name, :epoch, :version, :release, :arch]
+
+ commands :rpm => "rpm"
+
+ if command('rpm')
+ confine :true => begin
+ rpm('--version')
+ rescue Puppet::ExecutionFailure
+ false
+ else
+ true
+ end
+ end
+
+ def self.instances
+ packages = []
+
+ # rpm < 4.1 don't support --nosignature
+ output = rpm "--version"
+ sig = "--nosignature"
+ if output =~ /RPM version (([123].*)|(4\.0.*))/
+ sig = ""
end
- def self.instances
- packages = []
-
- # rpm < 4.1 don't support --nosignature
- output = rpm "--version"
- sig = "--nosignature"
- if output =~ /RPM version (([123].*)|(4\.0.*))/
- sig = ""
- end
-
- # list out all of the packages
- begin
- execpipe("#{command(:rpm)} -qa #{sig} --nodigest --qf '#{NEVRAFORMAT}\n'") { |process|
- # now turn each returned line into a package object
- process.each { |line|
- hash = nevra_to_hash(line)
- packages << new(hash)
- }
- }
- rescue Puppet::ExecutionFailure
- raise Puppet::Error, "Failed to list packages"
- end
-
- packages
+ # list out all of the packages
+ begin
+ execpipe("#{command(:rpm)} -qa #{sig} --nodigest --qf '#{NEVRAFORMAT}\n'") { |process|
+ # now turn each returned line into a package object
+ process.each { |line|
+ hash = nevra_to_hash(line)
+ packages << new(hash)
+ }
+ }
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error, "Failed to list packages"
end
- # Find the fully versioned package name and the version alone. Returns
- # a hash with entries :instance => fully versioned package name, and
- # :ensure => version-release
- def query
- #NOTE: Prior to a fix for issue 1243, this method potentially returned a cached value
- #IF YOU CALL THIS METHOD, IT WILL CALL RPM
- #Use get(:property) to check if cached values are available
- cmd = ["-q", @resource[:name], "--nosignature", "--nodigest", "--qf", "#{NEVRAFORMAT}\n"]
-
- begin
- output = rpm(*cmd)
- rescue Puppet::ExecutionFailure
- return nil
- end
-
- # FIXME: We could actually be getting back multiple packages
- # for multilib
- @property_hash.update(self.class.nevra_to_hash(output))
-
- @property_hash.dup
+ packages
+ end
+
+ # Find the fully versioned package name and the version alone. Returns
+ # a hash with entries :instance => fully versioned package name, and
+ # :ensure => version-release
+ def query
+ #NOTE: Prior to a fix for issue 1243, this method potentially returned a cached value
+ #IF YOU CALL THIS METHOD, IT WILL CALL RPM
+ #Use get(:property) to check if cached values are available
+ cmd = ["-q", @resource[:name], "--nosignature", "--nodigest", "--qf", "#{NEVRAFORMAT}\n"]
+
+ begin
+ output = rpm(*cmd)
+ rescue Puppet::ExecutionFailure
+ return nil
end
- # Here we just retrieve the version from the file specified in the source.
- def latest
- unless source = @resource[:source]
- @resource.fail "RPMs must specify a package source"
- end
+ # FIXME: We could actually be getting back multiple packages
+ # for multilib
+ @property_hash.update(self.class.nevra_to_hash(output))
- cmd = [command(:rpm), "-q", "--qf", "#{NEVRAFORMAT}\n", "-p", "#{@resource[:source]}"]
- h = self.class.nevra_to_hash(execfail(cmd, Puppet::Error))
- h[:ensure]
- end
+ @property_hash.dup
+ end
- def install
- source = nil
- unless source = @resource[:source]
- @resource.fail "RPMs must specify a package source"
- end
- # RPM gets pissy if you try to install an already
- # installed package
- if @resource.should(:ensure) == @property_hash[:ensure] or
- @resource.should(:ensure) == :latest && @property_hash[:ensure] == latest
- return
- end
-
- flag = "-i"
- flag = "-U" if @property_hash[:ensure] and @property_hash[:ensure] != :absent
-
- rpm flag, "--oldpackage", source
+ # Here we just retrieve the version from the file specified in the source.
+ def latest
+ unless source = @resource[:source]
+ @resource.fail "RPMs must specify a package source"
end
- def uninstall
- query unless get(:arch)
- nvr = "#{get(:name)}-#{get(:version)}-#{get(:release)}"
- arch = ".#{get(:arch)}"
- # If they specified an arch in the manifest, erase that Otherwise,
- # erase the arch we got back from the query. If multiple arches are
- # installed and only the package name is specified (without the
- # arch), this will uninstall all of them on successive runs of the
- # client, one after the other
- if @resource[:name][-arch.size, arch.size] == arch
- nvr += arch
- else
- nvr += ".#{get(:arch)}"
- end
- rpm "-e", nvr
- end
+ cmd = [command(:rpm), "-q", "--qf", "#{NEVRAFORMAT}\n", "-p", "#{@resource[:source]}"]
+ h = self.class.nevra_to_hash(execfail(cmd, Puppet::Error))
+ h[:ensure]
+ end
- def update
- self.install
+ def install
+ source = nil
+ unless source = @resource[:source]
+ @resource.fail "RPMs must specify a package source"
+ end
+ # RPM gets pissy if you try to install an already
+ # installed package
+ if @resource.should(:ensure) == @property_hash[:ensure] or
+ @resource.should(:ensure) == :latest && @property_hash[:ensure] == latest
+ return
end
- def self.nevra_to_hash(line)
- line.chomp!
- hash = {}
- NEVRA_FIELDS.zip(line.split) { |f, v| hash[f] = v }
- hash[:provider] = self.name
- hash[:ensure] = "#{hash[:version]}-#{hash[:release]}"
- hash
+ flag = "-i"
+ flag = "-U" if @property_hash[:ensure] and @property_hash[:ensure] != :absent
+
+ rpm flag, "--oldpackage", source
+ end
+
+ def uninstall
+ query unless get(:arch)
+ nvr = "#{get(:name)}-#{get(:version)}-#{get(:release)}"
+ arch = ".#{get(:arch)}"
+ # If they specified an arch in the manifest, erase that Otherwise,
+ # erase the arch we got back from the query. If multiple arches are
+ # installed and only the package name is specified (without the
+ # arch), this will uninstall all of them on successive runs of the
+ # client, one after the other
+ if @resource[:name][-arch.size, arch.size] == arch
+ nvr += arch
+ else
+ nvr += ".#{get(:arch)}"
end
+ rpm "-e", nvr
+ end
+
+ def update
+ self.install
+ end
+
+ def self.nevra_to_hash(line)
+ line.chomp!
+ hash = {}
+ NEVRA_FIELDS.zip(line.split) { |f, v| hash[f] = v }
+ hash[:provider] = self.name
+ hash[:ensure] = "#{hash[:version]}-#{hash[:release]}"
+ hash
+ end
end
diff --git a/lib/puppet/provider/package/rug.rb b/lib/puppet/provider/package/rug.rb
index 227edc7c2..7028cc9e5 100644
--- a/lib/puppet/provider/package/rug.rb
+++ b/lib/puppet/provider/package/rug.rb
@@ -1,52 +1,52 @@
Puppet::Type.type(:package).provide :rug, :parent => :rpm do
- desc "Support for suse ``rug`` package manager."
-
- has_feature :versionable
-
- commands :rug => "/usr/bin/rug"
- commands :rpm => "rpm"
- defaultfor :operatingsystem => [:suse, :sles]
- confine :operatingsystem => [:suse, :sles]
-
- # Install a package using 'rug'.
- def install
- should = @resource.should(:ensure)
- self.debug "Ensuring => #{should}"
- wanted = @resource[:name]
-
- # XXX: We don't actually deal with epochs here.
- case should
- when true, false, Symbol
- # pass
- else
- # Add the package version
- wanted += "-#{should}"
- end
- output = rug "--quiet", :install, "-y", wanted
-
- unless self.query
- raise Puppet::ExecutionFailure.new(
- "Could not find package #{self.name}"
- )
- end
+ desc "Support for suse ``rug`` package manager."
+
+ has_feature :versionable
+
+ commands :rug => "/usr/bin/rug"
+ commands :rpm => "rpm"
+ defaultfor :operatingsystem => [:suse, :sles]
+ confine :operatingsystem => [:suse, :sles]
+
+ # Install a package using 'rug'.
+ def install
+ should = @resource.should(:ensure)
+ self.debug "Ensuring => #{should}"
+ wanted = @resource[:name]
+
+ # XXX: We don't actually deal with epochs here.
+ case should
+ when true, false, Symbol
+ # pass
+ else
+ # Add the package version
+ wanted += "-#{should}"
end
+ output = rug "--quiet", :install, "-y", wanted
- # What's the latest package version available?
- def latest
- #rug can only get a list of *all* available packages?
- output = rug "list-updates"
-
- if output =~ /#{Regexp.escape @resource[:name]}\s*\|\s*([^\s\|]+)/
- return $1
- else
- # rug didn't find updates, pretend the current
- # version is the latest
- return @property_hash[:ensure]
- end
+ unless self.query
+ raise Puppet::ExecutionFailure.new(
+ "Could not find package #{self.name}"
+ )
end
-
- def update
- # rug install can be used for update, too
- self.install
+ end
+
+ # What's the latest package version available?
+ def latest
+ #rug can only get a list of *all* available packages?
+ output = rug "list-updates"
+
+ if output =~ /#{Regexp.escape @resource[:name]}\s*\|\s*([^\s\|]+)/
+ return $1
+ else
+ # rug didn't find updates, pretend the current
+ # version is the latest
+ return @property_hash[:ensure]
end
+ end
+
+ def update
+ # rug install can be used for update, too
+ self.install
+ end
end
diff --git a/lib/puppet/provider/package/sun.rb b/lib/puppet/provider/package/sun.rb
index c98636e11..05bbe9726 100755
--- a/lib/puppet/provider/package/sun.rb
+++ b/lib/puppet/provider/package/sun.rb
@@ -3,153 +3,153 @@
require 'puppet/provider/package'
Puppet::Type.type(:package).provide :sun, :parent => Puppet::Provider::Package do
- desc "Sun's packaging system. Requires that you specify the source for
- the packages you're managing."
- commands :pkginfo => "/usr/bin/pkginfo",
- :pkgadd => "/usr/sbin/pkgadd",
- :pkgrm => "/usr/sbin/pkgrm"
-
- confine :operatingsystem => :solaris
-
- defaultfor :operatingsystem => :solaris
-
- def self.instances
- packages = []
- hash = {}
- names = {
- "PKGINST" => :name,
- "NAME" => nil,
- "CATEGORY" => :category,
- "ARCH" => :platform,
- "VERSION" => :ensure,
- "BASEDIR" => :root,
- "HOTLINE" => nil,
- "EMAIL" => nil,
- "VENDOR" => :vendor,
- "DESC" => :description,
- "PSTAMP" => nil,
- "INSTDATE" => nil,
- "STATUS" => nil,
- "FILES" => nil
- }
-
- cmd = "#{command(:pkginfo)} -l"
-
- # list out all of the packages
- execpipe(cmd) { |process|
- # we're using the long listing, so each line is a separate
- # piece of information
- process.each { |line|
- case line
- when /^$/
- hash[:provider] = :sun
-
- packages << new(hash)
- hash = {}
- when /\s*(\w+):\s+(.+)/
- name = $1
- value = $2
- if names.include?(name)
- hash[names[name]] = value unless names[name].nil?
- end
- when /\s+\d+.+/
- # nothing; we're ignoring the FILES info
- end
- }
- }
- packages
- end
-
- # Get info on a package, optionally specifying a device.
- def info2hash(device = nil)
- names = {
- "PKGINST" => :name,
- "NAME" => nil,
- "CATEGORY" => :category,
- "ARCH" => :platform,
- "VERSION" => :ensure,
- "BASEDIR" => :root,
- "HOTLINE" => nil,
- "EMAIL" => nil,
- "VSTOCK" => nil,
- "VENDOR" => :vendor,
- "DESC" => :description,
- "PSTAMP" => nil,
- "INSTDATE" => nil,
- "STATUS" => nil,
- "FILES" => nil
- }
-
- hash = {}
- cmd = "#{command(:pkginfo)} -l"
- cmd += " -d #{device}" if device
- cmd += " #{@resource[:name]}"
-
- begin
- # list out all of the packages
- execpipe(cmd) { |process|
- # we're using the long listing, so each line is a separate
- # piece of information
- process.readlines.each { |line|
- case line
- when /^$/ # ignore
- when /\s*([A-Z]+):\s+(.+)/
- name = $1
- value = $2
- if names.include?(name)
- hash[names[name]] = value unless names[name].nil?
- end
- when /\s+\d+.+/
- # nothing; we're ignoring the FILES info
- end
- }
- }
- return hash
- rescue Puppet::ExecutionFailure => detail
- return {:ensure => :absent} if detail.message =~ /information for "#{Regexp.escape(@resource[:name])}" was not found/
- puts detail.backtrace if Puppet[:trace]
- raise Puppet::Error, "Unable to get information about package #{@resource[:name]} because of: #{detail}"
+ desc "Sun's packaging system. Requires that you specify the source for
+ the packages you're managing."
+ commands :pkginfo => "/usr/bin/pkginfo",
+ :pkgadd => "/usr/sbin/pkgadd",
+ :pkgrm => "/usr/sbin/pkgrm"
+
+ confine :operatingsystem => :solaris
+
+ defaultfor :operatingsystem => :solaris
+
+ def self.instances
+ packages = []
+ hash = {}
+ names = {
+ "PKGINST" => :name,
+ "NAME" => nil,
+ "CATEGORY" => :category,
+ "ARCH" => :platform,
+ "VERSION" => :ensure,
+ "BASEDIR" => :root,
+ "HOTLINE" => nil,
+ "EMAIL" => nil,
+ "VENDOR" => :vendor,
+ "DESC" => :description,
+ "PSTAMP" => nil,
+ "INSTDATE" => nil,
+ "STATUS" => nil,
+ "FILES" => nil
+ }
+
+ cmd = "#{command(:pkginfo)} -l"
+
+ # list out all of the packages
+ execpipe(cmd) { |process|
+ # we're using the long listing, so each line is a separate
+ # piece of information
+ process.each { |line|
+ case line
+ when /^$/
+ hash[:provider] = :sun
+
+ packages << new(hash)
+ hash = {}
+ when /\s*(\w+):\s+(.+)/
+ name = $1
+ value = $2
+ if names.include?(name)
+ hash[names[name]] = value unless names[name].nil?
+ end
+ when /\s+\d+.+/
+ # nothing; we're ignoring the FILES info
end
+ }
+ }
+ packages
+ end
+
+ # Get info on a package, optionally specifying a device.
+ def info2hash(device = nil)
+ names = {
+ "PKGINST" => :name,
+ "NAME" => nil,
+ "CATEGORY" => :category,
+ "ARCH" => :platform,
+ "VERSION" => :ensure,
+ "BASEDIR" => :root,
+ "HOTLINE" => nil,
+ "EMAIL" => nil,
+ "VSTOCK" => nil,
+ "VENDOR" => :vendor,
+ "DESC" => :description,
+ "PSTAMP" => nil,
+ "INSTDATE" => nil,
+ "STATUS" => nil,
+ "FILES" => nil
+ }
+
+ hash = {}
+ cmd = "#{command(:pkginfo)} -l"
+ cmd += " -d #{device}" if device
+ cmd += " #{@resource[:name]}"
+
+ begin
+ # list out all of the packages
+ execpipe(cmd) { |process|
+ # we're using the long listing, so each line is a separate
+ # piece of information
+ process.readlines.each { |line|
+ case line
+ when /^$/ # ignore
+ when /\s*([A-Z]+):\s+(.+)/
+ name = $1
+ value = $2
+ if names.include?(name)
+ hash[names[name]] = value unless names[name].nil?
+ end
+ when /\s+\d+.+/
+ # nothing; we're ignoring the FILES info
+ end
+ }
+ }
+ return hash
+ rescue Puppet::ExecutionFailure => detail
+ return {:ensure => :absent} if detail.message =~ /information for "#{Regexp.escape(@resource[:name])}" was not found/
+ puts detail.backtrace if Puppet[:trace]
+ raise Puppet::Error, "Unable to get information about package #{@resource[:name]} because of: #{detail}"
end
+ end
- def install
- raise Puppet::Error, "Sun packages must specify a package source" unless @resource[:source]
- cmd = []
+ def install
+ raise Puppet::Error, "Sun packages must specify a package source" unless @resource[:source]
+ cmd = []
- cmd << "-a" << @resource[:adminfile] if @resource[:adminfile]
+ cmd << "-a" << @resource[:adminfile] if @resource[:adminfile]
- cmd << "-r" << @resource[:responsefile] if @resource[:responsefile]
+ cmd << "-r" << @resource[:responsefile] if @resource[:responsefile]
- cmd << "-d" << @resource[:source]
- cmd << "-n" << @resource[:name]
+ cmd << "-d" << @resource[:source]
+ cmd << "-n" << @resource[:name]
- pkgadd cmd
- end
+ pkgadd cmd
+ end
- # Retrieve the version from the current package file.
- def latest
- hash = info2hash(@resource[:source])
- hash[:ensure]
- end
+ # Retrieve the version from the current package file.
+ def latest
+ hash = info2hash(@resource[:source])
+ hash[:ensure]
+ end
- def query
- info2hash()
- end
+ def query
+ info2hash()
+ end
- def uninstall
- command = ["-n"]
+ def uninstall
+ command = ["-n"]
- command << "-a" << @resource[:adminfile] if @resource[:adminfile]
+ command << "-a" << @resource[:adminfile] if @resource[:adminfile]
- command << @resource[:name]
- pkgrm command
- end
+ command << @resource[:name]
+ pkgrm command
+ end
- # Remove the old package, and install the new one. This will probably
- # often fail.
- def update
- self.uninstall if (@property_hash[:ensure] || info2hash()[:ensure]) != :absent
- self.install
- end
+ # Remove the old package, and install the new one. This will probably
+ # often fail.
+ def update
+ self.uninstall if (@property_hash[:ensure] || info2hash()[:ensure]) != :absent
+ self.install
+ end
end
diff --git a/lib/puppet/provider/package/sunfreeware.rb b/lib/puppet/provider/package/sunfreeware.rb
index d7bcd0982..53f03ed6e 100755
--- a/lib/puppet/provider/package/sunfreeware.rb
+++ b/lib/puppet/provider/package/sunfreeware.rb
@@ -1,11 +1,11 @@
# At this point, it's an exact copy of the Blastwave stuff.
Puppet::Type.type(:package).provide :sunfreeware, :parent => :blastwave, :source => :sun do
- desc "Package management using sunfreeware.com's ``pkg-get`` command on Solaris.
- At this point, support is exactly the same as ``blastwave`` support and
- has not actually been tested."
- commands :pkgget => "pkg-get"
+ desc "Package management using sunfreeware.com's ``pkg-get`` command on Solaris.
+ At this point, support is exactly the same as ``blastwave`` support and
+ has not actually been tested."
+ commands :pkgget => "pkg-get"
- confine :operatingsystem => :solaris
+ confine :operatingsystem => :solaris
end
diff --git a/lib/puppet/provider/package/up2date.rb b/lib/puppet/provider/package/up2date.rb
index 8780e7fd4..5ff32bedc 100644
--- a/lib/puppet/provider/package/up2date.rb
+++ b/lib/puppet/provider/package/up2date.rb
@@ -1,42 +1,42 @@
Puppet::Type.type(:package).provide :up2date, :parent => :rpm, :source => :rpm do
- desc "Support for Red Hat's proprietary ``up2date`` package update
- mechanism."
+ desc "Support for Red Hat's proprietary ``up2date`` package update
+ mechanism."
- commands :up2date => "/usr/sbin/up2date-nox"
+ commands :up2date => "/usr/sbin/up2date-nox"
- defaultfor :operatingsystem => [:redhat, :oel, :ovm],
- :lsbdistrelease => ["2.1", "3", "4"]
+ defaultfor :operatingsystem => [:redhat, :oel, :ovm],
+ :lsbdistrelease => ["2.1", "3", "4"]
- confine :operatingsystem => [:redhat, :oel, :ovm]
+ confine :operatingsystem => [:redhat, :oel, :ovm]
- # Install a package using 'up2date'.
- def install
- up2date "-u", @resource[:name]
+ # Install a package using 'up2date'.
+ def install
+ up2date "-u", @resource[:name]
- unless self.query
- raise Puppet::ExecutionFailure.new(
- "Could not find package #{self.name}"
- )
- end
+ unless self.query
+ raise Puppet::ExecutionFailure.new(
+ "Could not find package #{self.name}"
+ )
end
-
- # What's the latest package version available?
- def latest
- #up2date can only get a list of *all* available packages?
- output = up2date "--showall"
-
- if output =~ /^#{Regexp.escape @resource[:name]}-(\d+.*)\.\w+/
- return $1
- else
- # up2date didn't find updates, pretend the current
- # version is the latest
- return @property_hash[:ensure]
- end
+ end
+
+ # What's the latest package version available?
+ def latest
+ #up2date can only get a list of *all* available packages?
+ output = up2date "--showall"
+
+ if output =~ /^#{Regexp.escape @resource[:name]}-(\d+.*)\.\w+/
+ return $1
+ else
+ # up2date didn't find updates, pretend the current
+ # version is the latest
+ return @property_hash[:ensure]
end
+ end
- def update
- # Install in up2date can be used for update, too
- self.install
- end
+ def update
+ # Install in up2date can be used for update, too
+ self.install
+ end
end
diff --git a/lib/puppet/provider/package/urpmi.rb b/lib/puppet/provider/package/urpmi.rb
index a7732c4a2..88a17ccb4 100644
--- a/lib/puppet/provider/package/urpmi.rb
+++ b/lib/puppet/provider/package/urpmi.rb
@@ -1,60 +1,60 @@
Puppet::Type.type(:package).provide :urpmi, :parent => :rpm, :source => :rpm do
- desc "Support via ``urpmi``."
- commands :urpmi => "urpmi", :urpmq => "urpmq", :rpm => "rpm"
-
- if command('rpm')
- confine :true => begin
- rpm('-ql', 'rpm')
- rescue Puppet::ExecutionFailure
- false
- else
- true
- end
+ desc "Support via ``urpmi``."
+ commands :urpmi => "urpmi", :urpmq => "urpmq", :rpm => "rpm"
+
+ if command('rpm')
+ confine :true => begin
+ rpm('-ql', 'rpm')
+ rescue Puppet::ExecutionFailure
+ false
+ else
+ true
+ end
+ end
+
+ defaultfor :operatingsystem => [:mandriva, :mandrake]
+
+ has_feature :versionable
+
+ def install
+ should = @resource.should(:ensure)
+ self.debug "Ensuring => #{should}"
+ wanted = @resource[:name]
+
+ # XXX: We don't actually deal with epochs here.
+ case should
+ when true, false, Symbol
+ # pass
+ else
+ # Add the package version
+ wanted += "-#{should}"
end
- defaultfor :operatingsystem => [:mandriva, :mandrake]
+ output = urpmi "--auto", wanted
- has_feature :versionable
-
- def install
- should = @resource.should(:ensure)
- self.debug "Ensuring => #{should}"
- wanted = @resource[:name]
-
- # XXX: We don't actually deal with epochs here.
- case should
- when true, false, Symbol
- # pass
- else
- # Add the package version
- wanted += "-#{should}"
- end
-
- output = urpmi "--auto", wanted
-
- unless self.query
- raise Puppet::Error.new(
- "Could not find package #{self.name}"
- )
- end
+ unless self.query
+ raise Puppet::Error.new(
+ "Could not find package #{self.name}"
+ )
end
-
- # What's the latest package version available?
- def latest
- output = urpmq "-S", @resource[:name]
-
- if output =~ /^#{Regexp.escape @resource[:name]}\s+:\s+.*\(\s+(\S+)\s+\)/
- return $1
- else
- # urpmi didn't find updates, pretend the current
- # version is the latest
- return @resource[:ensure]
- end
+ end
+
+ # What's the latest package version available?
+ def latest
+ output = urpmq "-S", @resource[:name]
+
+ if output =~ /^#{Regexp.escape @resource[:name]}\s+:\s+.*\(\s+(\S+)\s+\)/
+ return $1
+ else
+ # urpmi didn't find updates, pretend the current
+ # version is the latest
+ return @resource[:ensure]
end
+ end
- def update
- # Install in urpmi can be used for update, too
- self.install
- end
+ def update
+ # Install in urpmi can be used for update, too
+ self.install
+ end
end
diff --git a/lib/puppet/provider/package/yum.rb b/lib/puppet/provider/package/yum.rb
index 17981f03c..07f68ddb1 100755
--- a/lib/puppet/provider/package/yum.rb
+++ b/lib/puppet/provider/package/yum.rb
@@ -1,100 +1,100 @@
Puppet::Type.type(:package).provide :yum, :parent => :rpm, :source => :rpm do
- desc "Support via ``yum``."
-
- has_feature :versionable
-
- commands :yum => "yum", :rpm => "rpm", :python => "python"
-
- YUMHELPER = File::join(File::dirname(__FILE__), "yumhelper.py")
-
- attr_accessor :latest_info
-
- if command('rpm')
- confine :true => begin
- rpm('--version')
- rescue Puppet::ExecutionFailure
- false
- else
- true
- end
- end
-
- defaultfor :operatingsystem => [:fedora, :centos, :redhat]
-
- def self.prefetch(packages)
- raise Puppet::Error, "The yum provider can only be used as root" if Process.euid != 0
- super
- return unless packages.detect { |name, package| package.should(:ensure) == :latest }
-
- # collect our 'latest' info
- updates = {}
- python(YUMHELPER).each_line do |l|
- l.chomp!
- next if l.empty?
- if l[0,4] == "_pkg"
- hash = nevra_to_hash(l[5..-1])
- [hash[:name], "#{hash[:name]}.#{hash[:arch]}"].each do |n|
- updates[n] ||= []
- updates[n] << hash
- end
- end
- end
-
- # Add our 'latest' info to the providers.
- packages.each do |name, package|
- if info = updates[package[:name]]
- package.provider.latest_info = info[0]
- end
+ desc "Support via ``yum``."
+
+ has_feature :versionable
+
+ commands :yum => "yum", :rpm => "rpm", :python => "python"
+
+ YUMHELPER = File::join(File::dirname(__FILE__), "yumhelper.py")
+
+ attr_accessor :latest_info
+
+ if command('rpm')
+ confine :true => begin
+ rpm('--version')
+ rescue Puppet::ExecutionFailure
+ false
+ else
+ true
+ end
+ end
+
+ defaultfor :operatingsystem => [:fedora, :centos, :redhat]
+
+ def self.prefetch(packages)
+ raise Puppet::Error, "The yum provider can only be used as root" if Process.euid != 0
+ super
+ return unless packages.detect { |name, package| package.should(:ensure) == :latest }
+
+ # collect our 'latest' info
+ updates = {}
+ python(YUMHELPER).each_line do |l|
+ l.chomp!
+ next if l.empty?
+ if l[0,4] == "_pkg"
+ hash = nevra_to_hash(l[5..-1])
+ [hash[:name], "#{hash[:name]}.#{hash[:arch]}"].each do |n|
+ updates[n] ||= []
+ updates[n] << hash
end
+ end
end
- def install
- should = @resource.should(:ensure)
- self.debug "Ensuring => #{should}"
- wanted = @resource[:name]
-
- # XXX: We don't actually deal with epochs here.
- case should
- when true, false, Symbol
- # pass
- should = nil
- else
- # Add the package version
- wanted += "-#{should}"
- end
-
- output = yum "-d", "0", "-e", "0", "-y", :install, wanted
-
- is = self.query
- raise Puppet::Error, "Could not find package #{self.name}" unless is
-
- # FIXME: Should we raise an exception even if should == :latest
- # and yum updated us to a version other than @param_hash[:ensure] ?
- raise Puppet::Error, "Failed to update to version #{should}, got version #{is[:ensure]} instead" if should && should != is[:ensure]
+ # Add our 'latest' info to the providers.
+ packages.each do |name, package|
+ if info = updates[package[:name]]
+ package.provider.latest_info = info[0]
+ end
end
-
- # What's the latest package version available?
- def latest
- upd = latest_info
- unless upd.nil?
- # FIXME: there could be more than one update for a package
- # because of multiarch
- return "#{upd[:version]}-#{upd[:release]}"
- else
- # Yum didn't find updates, pretend the current
- # version is the latest
- raise Puppet::DevError, "Tried to get latest on a missing package" if properties[:ensure] == :absent
- return properties[:ensure]
- end
+ end
+
+ def install
+ should = @resource.should(:ensure)
+ self.debug "Ensuring => #{should}"
+ wanted = @resource[:name]
+
+ # XXX: We don't actually deal with epochs here.
+ case should
+ when true, false, Symbol
+ # pass
+ should = nil
+ else
+ # Add the package version
+ wanted += "-#{should}"
end
- def update
- # Install in yum can be used for update, too
- self.install
+ output = yum "-d", "0", "-e", "0", "-y", :install, wanted
+
+ is = self.query
+ raise Puppet::Error, "Could not find package #{self.name}" unless is
+
+ # FIXME: Should we raise an exception even if should == :latest
+ # and yum updated us to a version other than @param_hash[:ensure] ?
+ raise Puppet::Error, "Failed to update to version #{should}, got version #{is[:ensure]} instead" if should && should != is[:ensure]
+ end
+
+ # What's the latest package version available?
+ def latest
+ upd = latest_info
+ unless upd.nil?
+ # FIXME: there could be more than one update for a package
+ # because of multiarch
+ return "#{upd[:version]}-#{upd[:release]}"
+ else
+ # Yum didn't find updates, pretend the current
+ # version is the latest
+ raise Puppet::DevError, "Tried to get latest on a missing package" if properties[:ensure] == :absent
+ return properties[:ensure]
end
+ end
- def purge
- yum "-y", :erase, @resource[:name]
- end
+ def update
+ # Install in yum can be used for update, too
+ self.install
+ end
+
+ def purge
+ yum "-y", :erase, @resource[:name]
+ end
end
diff --git a/lib/puppet/provider/package/zypper.rb b/lib/puppet/provider/package/zypper.rb
index 9f7386b20..d56c72549 100644
--- a/lib/puppet/provider/package/zypper.rb
+++ b/lib/puppet/provider/package/zypper.rb
@@ -1,52 +1,52 @@
Puppet::Type.type(:package).provide :zypper, :parent => :rpm do
- desc "Support for SuSE ``zypper`` package manager. Found in SLES10sp2+ and SLES11"
-
- has_feature :versionable
-
- commands :zypper => "/usr/bin/zypper"
- commands :rpm => "rpm"
-
- confine :operatingsystem => [:suse, :sles, :sled, :opensuse]
-
- # Install a package using 'zypper'.
- def install
- should = @resource.should(:ensure)
- self.debug "Ensuring => #{should}"
- wanted = @resource[:name]
-
- # XXX: We don't actually deal with epochs here.
- case should
- when true, false, Symbol
- # pass
- else
- # Add the package version
- wanted = "#{wanted}-#{should}"
- end
- output = zypper "--quiet", :install, "-l", "-y", wanted
-
- unless self.query
- raise Puppet::ExecutionFailure.new(
- "Could not find package #{self.name}"
- )
- end
- end
+ desc "Support for SuSE ``zypper`` package manager. Found in SLES10sp2+ and SLES11"
+
+ has_feature :versionable
+
+ commands :zypper => "/usr/bin/zypper"
+ commands :rpm => "rpm"
+
+ confine :operatingsystem => [:suse, :sles, :sled, :opensuse]
- # What's the latest package version available?
- def latest
- #zypper can only get a list of *all* available packages?
- output = zypper "list-updates"
-
- if output =~ /#{Regexp.escape @resource[:name]}\s*\|\s*([^\s\|]+)/
- return $1
- else
- # zypper didn't find updates, pretend the current
- # version is the latest
- return @property_hash[:ensure]
- end
+ # Install a package using 'zypper'.
+ def install
+ should = @resource.should(:ensure)
+ self.debug "Ensuring => #{should}"
+ wanted = @resource[:name]
+
+ # XXX: We don't actually deal with epochs here.
+ case should
+ when true, false, Symbol
+ # pass
+ else
+ # Add the package version
+ wanted = "#{wanted}-#{should}"
end
+ output = zypper "--quiet", :install, "-l", "-y", wanted
- def update
- # zypper install can be used for update, too
- self.install
+ unless self.query
+ raise Puppet::ExecutionFailure.new(
+ "Could not find package #{self.name}"
+ )
+ end
+ end
+
+ # What's the latest package version available?
+ def latest
+ #zypper can only get a list of *all* available packages?
+ output = zypper "list-updates"
+
+ if output =~ /#{Regexp.escape @resource[:name]}\s*\|\s*([^\s\|]+)/
+ return $1
+ else
+ # zypper didn't find updates, pretend the current
+ # version is the latest
+ return @property_hash[:ensure]
end
+ end
+
+ def update
+ # zypper install can be used for update, too
+ self.install
+ end
end
diff --git a/lib/puppet/provider/parsedfile.rb b/lib/puppet/provider/parsedfile.rb
index 811607abb..ffd36e59f 100755
--- a/lib/puppet/provider/parsedfile.rb
+++ b/lib/puppet/provider/parsedfile.rb
@@ -11,124 +11,124 @@ require 'puppet/util/fileparsing'
# Once the provider prefetches the data, it's the resource's job to copy
# that data over to the @is variables.
class Puppet::Provider::ParsedFile < Puppet::Provider
- extend Puppet::Util::FileParsing
+ extend Puppet::Util::FileParsing
- class << self
- attr_accessor :default_target, :target
- end
-
- attr_accessor :property_hash
+ class << self
+ attr_accessor :default_target, :target
+ end
- def self.clean(hash)
- newhash = hash.dup
- [:record_type, :on_disk].each do |p|
- newhash.delete(p) if newhash.include?(p)
- end
+ attr_accessor :property_hash
- newhash
+ def self.clean(hash)
+ newhash = hash.dup
+ [:record_type, :on_disk].each do |p|
+ newhash.delete(p) if newhash.include?(p)
end
- def self.clear
- @target_objects.clear
- @records.clear
- end
+ newhash
+ end
- def self.filetype
- @filetype ||= Puppet::Util::FileType.filetype(:flat)
- end
+ def self.clear
+ @target_objects.clear
+ @records.clear
+ end
- def self.filetype=(type)
- if type.is_a?(Class)
- @filetype = type
- elsif klass = Puppet::Util::FileType.filetype(type)
- @filetype = klass
- else
- raise ArgumentError, "Invalid filetype #{type}"
- end
+ def self.filetype
+ @filetype ||= Puppet::Util::FileType.filetype(:flat)
+ end
+
+ def self.filetype=(type)
+ if type.is_a?(Class)
+ @filetype = type
+ elsif klass = Puppet::Util::FileType.filetype(type)
+ @filetype = klass
+ else
+ raise ArgumentError, "Invalid filetype #{type}"
end
+ end
- # Flush all of the targets for which there are modified records. The only
- # reason we pass a record here is so that we can add it to the stack if
- # necessary -- it's passed from the instance calling 'flush'.
- def self.flush(record)
- # Make sure this record is on the list to be flushed.
- unless record[:on_disk]
- record[:on_disk] = true
- @records << record
-
- # If we've just added the record, then make sure our
- # target will get flushed.
- modified(record[:target] || default_target)
- end
+ # Flush all of the targets for which there are modified records. The only
+ # reason we pass a record here is so that we can add it to the stack if
+ # necessary -- it's passed from the instance calling 'flush'.
+ def self.flush(record)
+ # Make sure this record is on the list to be flushed.
+ unless record[:on_disk]
+ record[:on_disk] = true
+ @records << record
- return unless defined?(@modified) and ! @modified.empty?
+ # If we've just added the record, then make sure our
+ # target will get flushed.
+ modified(record[:target] || default_target)
+ end
- flushed = []
- @modified.sort { |a,b| a.to_s <=> b.to_s }.uniq.each do |target|
- Puppet.debug "Flushing #{@resource_type.name} provider target #{target}"
- flush_target(target)
- flushed << target
- end
+ return unless defined?(@modified) and ! @modified.empty?
- @modified.reject! { |t| flushed.include?(t) }
+ flushed = []
+ @modified.sort { |a,b| a.to_s <=> b.to_s }.uniq.each do |target|
+ Puppet.debug "Flushing #{@resource_type.name} provider target #{target}"
+ flush_target(target)
+ flushed << target
end
- # Make sure our file is backed up, but only back it up once per transaction.
- # We cheat and rely on the fact that @records is created on each prefetch.
- def self.backup_target(target)
- return nil unless target_object(target).respond_to?(:backup)
+ @modified.reject! { |t| flushed.include?(t) }
+ end
- @backup_stats ||= {}
- return nil if @backup_stats[target] == @records.object_id
+ # Make sure our file is backed up, but only back it up once per transaction.
+ # We cheat and rely on the fact that @records is created on each prefetch.
+ def self.backup_target(target)
+ return nil unless target_object(target).respond_to?(:backup)
- target_object(target).backup
- @backup_stats[target] = @records.object_id
- end
+ @backup_stats ||= {}
+ return nil if @backup_stats[target] == @records.object_id
- # Flush all of the records relating to a specific target.
- def self.flush_target(target)
- backup_target(target)
+ target_object(target).backup
+ @backup_stats[target] = @records.object_id
+ end
- records = target_records(target).reject { |r|
- r[:ensure] == :absent
- }
- target_object(target).write(to_file(records))
- end
+ # Flush all of the records relating to a specific target.
+ def self.flush_target(target)
+ backup_target(target)
- # Return the header placed at the top of each generated file, warning
- # users that modifying this file manually is probably a bad idea.
- def self.header
+ records = target_records(target).reject { |r|
+ r[:ensure] == :absent
+ }
+ target_object(target).write(to_file(records))
+ end
+
+ # Return the header placed at the top of each generated file, warning
+ # users that modifying this file manually is probably a bad idea.
+ def self.header
%{# HEADER: This file was autogenerated at #{Time.now}
# HEADER: by puppet. While it can still be managed manually, it
# HEADER: is definitely not recommended.\n}
- end
-
- # Add another type var.
- def self.initvars
- @records = []
- @target_objects = {}
-
- @target = nil
-
- # Default to flat files
- @filetype ||= Puppet::Util::FileType.filetype(:flat)
- super
- end
-
- # Return a list of all of the records we can find.
- def self.instances
- targets.collect do |target|
- prefetch_target(target)
- end.flatten.reject { |r| skip_record?(r) }.collect do |record|
- new(record)
- end
- end
-
- # Override the default method with a lot more functionality.
- def self.mk_resource_methods
- [resource_type.validproperties, resource_type.parameters].flatten.each do |attr|
- attr = symbolize(attr)
- define_method(attr) do
+ end
+
+ # Add another type var.
+ def self.initvars
+ @records = []
+ @target_objects = {}
+
+ @target = nil
+
+ # Default to flat files
+ @filetype ||= Puppet::Util::FileType.filetype(:flat)
+ super
+ end
+
+ # Return a list of all of the records we can find.
+ def self.instances
+ targets.collect do |target|
+ prefetch_target(target)
+ end.flatten.reject { |r| skip_record?(r) }.collect do |record|
+ new(record)
+ end
+ end
+
+ # Override the default method with a lot more functionality.
+ def self.mk_resource_methods
+ [resource_type.validproperties, resource_type.parameters].flatten.each do |attr|
+ attr = symbolize(attr)
+ define_method(attr) do
# if @property_hash.empty?
# # Note that this swaps the provider out from under us.
# prefetch
@@ -138,235 +138,235 @@ class Puppet::Provider::ParsedFile < Puppet::Provider
# return @resource.provider.send(attr)
# end
# end
- # If it's not a valid field for this record type (which can happen
- # when different platforms support different fields), then just
- # return the should value, so the resource shuts up.
- if @property_hash[attr] or self.class.valid_attr?(self.class.name, attr)
- @property_hash[attr] || :absent
- else
- if defined?(@resource)
- @resource.should(attr)
- else
- nil
- end
- end
- end
-
- define_method(attr.to_s + "=") do |val|
- mark_target_modified
- @property_hash[attr] = val
- end
- end
- end
-
- # Always make the resource methods.
- def self.resource_type=(resource)
- super
- mk_resource_methods
- end
-
- # Mark a target as modified so we know to flush it. This only gets
- # used within the attr= methods.
- def self.modified(target)
- @modified ||= []
- @modified << target unless @modified.include?(target)
- end
-
- # Retrieve all of the data from disk. There are three ways to know
- # which files to retrieve: We might have a list of file objects already
- # set up, there might be instances of our associated resource and they
- # will have a path parameter set, and we will have a default path
- # set. We need to turn those three locations into a list of files,
- # prefetch each one, and make sure they're associated with each appropriate
- # resource instance.
- def self.prefetch(resources = nil)
- # Reset the record list.
- @records = prefetch_all_targets(resources)
-
- match_providers_with_resources(resources)
- end
-
- def self.match_providers_with_resources(resources)
- return unless resources
- matchers = resources.dup
- @records.each do |record|
- # Skip things like comments and blank lines
- next if skip_record?(record)
-
- if name = record[:name] and resource = resources[name]
- resource.provider = new(record)
- elsif respond_to?(:match)
- if resource = match(record, matchers)
- # Remove this resource from circulation so we don't unnecessarily try to match
- matchers.delete(resource.title)
- record[:name] = resource[:name]
- resource.provider = new(record)
- end
- end
- end
- end
-
- def self.prefetch_all_targets(resources)
- records = []
- targets(resources).each do |target|
- records += prefetch_target(target)
+ # If it's not a valid field for this record type (which can happen
+ # when different platforms support different fields), then just
+ # return the should value, so the resource shuts up.
+ if @property_hash[attr] or self.class.valid_attr?(self.class.name, attr)
+ @property_hash[attr] || :absent
+ else
+ if defined?(@resource)
+ @resource.should(attr)
+ else
+ nil
+ end
end
- records
- end
+ end
- # Prefetch an individual target.
- def self.prefetch_target(target)
- target_records = retrieve(target).each do |r|
- r[:on_disk] = true
- r[:target] = target
- r[:ensure] = :present
+ define_method(attr.to_s + "=") do |val|
+ mark_target_modified
+ @property_hash[attr] = val
+ end
+ end
+ end
+
+ # Always make the resource methods.
+ def self.resource_type=(resource)
+ super
+ mk_resource_methods
+ end
+
+ # Mark a target as modified so we know to flush it. This only gets
+ # used within the attr= methods.
+ def self.modified(target)
+ @modified ||= []
+ @modified << target unless @modified.include?(target)
+ end
+
+ # Retrieve all of the data from disk. There are three ways to know
+ # which files to retrieve: We might have a list of file objects already
+ # set up, there might be instances of our associated resource and they
+ # will have a path parameter set, and we will have a default path
+ # set. We need to turn those three locations into a list of files,
+ # prefetch each one, and make sure they're associated with each appropriate
+ # resource instance.
+ def self.prefetch(resources = nil)
+ # Reset the record list.
+ @records = prefetch_all_targets(resources)
+
+ match_providers_with_resources(resources)
+ end
+
+ def self.match_providers_with_resources(resources)
+ return unless resources
+ matchers = resources.dup
+ @records.each do |record|
+ # Skip things like comments and blank lines
+ next if skip_record?(record)
+
+ if name = record[:name] and resource = resources[name]
+ resource.provider = new(record)
+ elsif respond_to?(:match)
+ if resource = match(record, matchers)
+ # Remove this resource from circulation so we don't unnecessarily try to match
+ matchers.delete(resource.title)
+ record[:name] = resource[:name]
+ resource.provider = new(record)
end
-
- target_records = prefetch_hook(target_records) if respond_to?(:prefetch_hook)
-
- raise Puppet::DevError, "Prefetching #{target} for provider #{self.name} returned nil" unless target_records
-
- target_records
- end
-
- # Is there an existing record with this name?
- def self.record?(name)
- return nil unless @records
- @records.find { |r| r[:name] == name }
- end
-
- # Retrieve the text for the file. Returns nil in the unlikely
- # event that it doesn't exist.
- def self.retrieve(path)
- # XXX We need to be doing something special here in case of failure.
- text = target_object(path).read
- if text.nil? or text == ""
- # there is no file
- return []
- else
- # Set the target, for logging.
- old = @target
- begin
- @target = path
- return self.parse(text)
- rescue Puppet::Error => detail
- detail.file = @target
- raise detail
- ensure
- @target = old
- end
+ end
+ end
+ end
+
+ def self.prefetch_all_targets(resources)
+ records = []
+ targets(resources).each do |target|
+ records += prefetch_target(target)
+ end
+ records
+ end
+
+ # Prefetch an individual target.
+ def self.prefetch_target(target)
+ target_records = retrieve(target).each do |r|
+ r[:on_disk] = true
+ r[:target] = target
+ r[:ensure] = :present
+ end
+
+ target_records = prefetch_hook(target_records) if respond_to?(:prefetch_hook)
+
+ raise Puppet::DevError, "Prefetching #{target} for provider #{self.name} returned nil" unless target_records
+
+ target_records
+ end
+
+ # Is there an existing record with this name?
+ def self.record?(name)
+ return nil unless @records
+ @records.find { |r| r[:name] == name }
+ end
+
+ # Retrieve the text for the file. Returns nil in the unlikely
+ # event that it doesn't exist.
+ def self.retrieve(path)
+ # XXX We need to be doing something special here in case of failure.
+ text = target_object(path).read
+ if text.nil? or text == ""
+ # there is no file
+ return []
+ else
+ # Set the target, for logging.
+ old = @target
+ begin
+ @target = path
+ return self.parse(text)
+ rescue Puppet::Error => detail
+ detail.file = @target
+ raise detail
+ ensure
+ @target = old
+ end
+ end
+ end
+
+ # Should we skip the record? Basically, we skip text records.
+ # This is only here so subclasses can override it.
+ def self.skip_record?(record)
+ record_type(record[:record_type]).text?
+ end
+
+ # Initialize the object if necessary.
+ def self.target_object(target)
+ @target_objects[target] ||= filetype.new(target)
+
+ @target_objects[target]
+ end
+
+ # Find all of the records for a given target
+ def self.target_records(target)
+ @records.find_all { |r| r[:target] == target }
+ end
+
+ # Find a list of all of the targets that we should be reading. This is
+ # used to figure out what targets we need to prefetch.
+ def self.targets(resources = nil)
+ targets = []
+ # First get the default target
+ raise Puppet::DevError, "Parsed Providers must define a default target" unless self.default_target
+ targets << self.default_target
+
+ # Then get each of the file objects
+ targets += @target_objects.keys
+
+ # Lastly, check the file from any resource instances
+ if resources
+ resources.each do |name, resource|
+ if value = resource.should(:target)
+ targets << value
end
+ end
end
- # Should we skip the record? Basically, we skip text records.
- # This is only here so subclasses can override it.
- def self.skip_record?(record)
- record_type(record[:record_type]).text?
- end
+ targets.uniq.compact
+ end
- # Initialize the object if necessary.
- def self.target_object(target)
- @target_objects[target] ||= filetype.new(target)
+ def self.to_file(records)
+ text = super
+ header + text
+ end
- @target_objects[target]
+ def create
+ @resource.class.validproperties.each do |property|
+ if value = @resource.should(property)
+ @property_hash[property] = value
+ end
end
+ mark_target_modified
+ (@resource.class.name.to_s + "_created").intern
+ end
- # Find all of the records for a given target
- def self.target_records(target)
- @records.find_all { |r| r[:target] == target }
- end
+ def destroy
+ # We use the method here so it marks the target as modified.
+ self.ensure = :absent
+ (@resource.class.name.to_s + "_deleted").intern
+ end
- # Find a list of all of the targets that we should be reading. This is
- # used to figure out what targets we need to prefetch.
- def self.targets(resources = nil)
- targets = []
- # First get the default target
- raise Puppet::DevError, "Parsed Providers must define a default target" unless self.default_target
- targets << self.default_target
-
- # Then get each of the file objects
- targets += @target_objects.keys
-
- # Lastly, check the file from any resource instances
- if resources
- resources.each do |name, resource|
- if value = resource.should(:target)
- targets << value
- end
- end
- end
+ def exists?
+ !(@property_hash[:ensure] == :absent or @property_hash[:ensure].nil?)
+ end
- targets.uniq.compact
- end
+ # Write our data to disk.
+ def flush
+ # Make sure we've got a target and name set.
- def self.to_file(records)
- text = super
- header + text
+ # If the target isn't set, then this is our first modification, so
+ # mark it for flushing.
+ unless @property_hash[:target]
+ @property_hash[:target] = @resource.should(:target) || self.class.default_target
+ self.class.modified(@property_hash[:target])
end
+ @property_hash[:name] ||= @resource.name
- def create
- @resource.class.validproperties.each do |property|
- if value = @resource.should(property)
- @property_hash[property] = value
- end
- end
- mark_target_modified
- (@resource.class.name.to_s + "_created").intern
- end
-
- def destroy
- # We use the method here so it marks the target as modified.
- self.ensure = :absent
- (@resource.class.name.to_s + "_deleted").intern
- end
-
- def exists?
- !(@property_hash[:ensure] == :absent or @property_hash[:ensure].nil?)
- end
-
- # Write our data to disk.
- def flush
- # Make sure we've got a target and name set.
+ self.class.flush(@property_hash)
- # If the target isn't set, then this is our first modification, so
- # mark it for flushing.
- unless @property_hash[:target]
- @property_hash[:target] = @resource.should(:target) || self.class.default_target
- self.class.modified(@property_hash[:target])
- end
- @property_hash[:name] ||= @resource.name
-
- self.class.flush(@property_hash)
-
- #@property_hash = {}
- end
+ #@property_hash = {}
+ end
- def initialize(record)
- super
+ def initialize(record)
+ super
- # The 'record' could be a resource or a record, depending on how the provider
- # is initialized. If we got an empty property hash (probably because the resource
- # is just being initialized), then we want to set up some defualts.
- @property_hash = self.class.record?(resource[:name]) || {:record_type => self.class.name, :ensure => :absent} if @property_hash.empty?
- end
+ # The 'record' could be a resource or a record, depending on how the provider
+ # is initialized. If we got an empty property hash (probably because the resource
+ # is just being initialized), then we want to set up some defualts.
+ @property_hash = self.class.record?(resource[:name]) || {:record_type => self.class.name, :ensure => :absent} if @property_hash.empty?
+ end
- # Retrieve the current state from disk.
- def prefetch
- raise Puppet::DevError, "Somehow got told to prefetch with no resource set" unless @resource
- self.class.prefetch(@resource[:name] => @resource)
- end
+ # Retrieve the current state from disk.
+ def prefetch
+ raise Puppet::DevError, "Somehow got told to prefetch with no resource set" unless @resource
+ self.class.prefetch(@resource[:name] => @resource)
+ end
- def record_type
- @property_hash[:record_type]
- end
+ def record_type
+ @property_hash[:record_type]
+ end
- private
+ private
- # Mark both the resource and provider target as modified.
- def mark_target_modified
- if defined?(@resource) and restarget = @resource.should(:target) and restarget != @property_hash[:target]
- self.class.modified(restarget)
- end
- self.class.modified(@property_hash[:target]) if @property_hash[:target] != :absent and @property_hash[:target]
+ # Mark both the resource and provider target as modified.
+ def mark_target_modified
+ if defined?(@resource) and restarget = @resource.should(:target) and restarget != @property_hash[:target]
+ self.class.modified(restarget)
end
+ self.class.modified(@property_hash[:target]) if @property_hash[:target] != :absent and @property_hash[:target]
+ end
end
diff --git a/lib/puppet/provider/selboolean/getsetsebool.rb b/lib/puppet/provider/selboolean/getsetsebool.rb
index 259d9471e..cacc41386 100644
--- a/lib/puppet/provider/selboolean/getsetsebool.rb
+++ b/lib/puppet/provider/selboolean/getsetsebool.rb
@@ -1,47 +1,47 @@
Puppet::Type.type(:selboolean).provide(:getsetsebool) do
- desc "Manage SELinux booleans using the getsebool and setsebool binaries."
+ desc "Manage SELinux booleans using the getsebool and setsebool binaries."
- commands :getsebool => "/usr/sbin/getsebool"
- commands :setsebool => "/usr/sbin/setsebool"
+ commands :getsebool => "/usr/sbin/getsebool"
+ commands :setsebool => "/usr/sbin/setsebool"
- def value
- self.debug "Retrieving value of selboolean #{@resource[:name]}"
+ def value
+ self.debug "Retrieving value of selboolean #{@resource[:name]}"
- status = getsebool(@resource[:name])
+ status = getsebool(@resource[:name])
- if status =~ / off$/
- return :off
- elsif status =~ / on$/ then
- return :on
- else
- status.chomp!
- raise Puppet::Error, "Invalid response '#{status}' returned from getsebool"
- end
+ if status =~ / off$/
+ return :off
+ elsif status =~ / on$/ then
+ return :on
+ else
+ status.chomp!
+ raise Puppet::Error, "Invalid response '#{status}' returned from getsebool"
end
+ end
- def value=(new)
- persist = ""
- if @resource[:persistent] == :true
- self.debug "Enabling persistence"
- persist = "-P"
- end
- execoutput("#{command(:setsebool)} #{persist} #{@resource[:name]} #{new}")
- :file_changed
+ def value=(new)
+ persist = ""
+ if @resource[:persistent] == :true
+ self.debug "Enabling persistence"
+ persist = "-P"
end
+ execoutput("#{command(:setsebool)} #{persist} #{@resource[:name]} #{new}")
+ :file_changed
+ end
- # Required workaround, since SELinux policy prevents setsebool
- # from writing to any files, even tmp, preventing the standard
- # 'setsebool("...")' construct from working.
+ # Required workaround, since SELinux policy prevents setsebool
+ # from writing to any files, even tmp, preventing the standard
+ # 'setsebool("...")' construct from working.
- def execoutput (cmd)
- output = ''
- begin
- execpipe(cmd) do |out|
- output = out.readlines.join('').chomp!
- end
- rescue Puppet::ExecutionFailure
- raise Puppet::ExecutionFailure, output.split("\n")[0]
- end
- output
+ def execoutput (cmd)
+ output = ''
+ begin
+ execpipe(cmd) do |out|
+ output = out.readlines.join('').chomp!
+ end
+ rescue Puppet::ExecutionFailure
+ raise Puppet::ExecutionFailure, output.split("\n")[0]
end
+ output
+ end
end
diff --git a/lib/puppet/provider/selmodule/semodule.rb b/lib/puppet/provider/selmodule/semodule.rb
index d6bf09a6a..64197156f 100644
--- a/lib/puppet/provider/selmodule/semodule.rb
+++ b/lib/puppet/provider/selmodule/semodule.rb
@@ -1,135 +1,135 @@
Puppet::Type.type(:selmodule).provide(:semodule) do
- desc "Manage SELinux policy modules using the semodule binary."
+ desc "Manage SELinux policy modules using the semodule binary."
- commands :semodule => "/usr/sbin/semodule"
+ commands :semodule => "/usr/sbin/semodule"
- def create
- begin
- execoutput("#{command(:semodule)} --install #{selmod_name_to_filename}")
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not load policy module: #{detail}";
- end
- :true
- end
-
- def destroy
- execoutput("#{command(:semodule)} --remove #{@resource[:name]}")
+ def create
+ begin
+ execoutput("#{command(:semodule)} --install #{selmod_name_to_filename}")
rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not remove policy module: #{detail}";
+ raise Puppet::Error, "Could not load policy module: #{detail}";
end
-
- def exists?
- self.debug "Checking for module #{@resource[:name]}"
- execpipe("#{command(:semodule)} --list") do |out|
- out.each do |line|
- if line =~ /#{@resource[:name]}\b/
- return :true
- end
- end
+ :true
+ end
+
+ def destroy
+ execoutput("#{command(:semodule)} --remove #{@resource[:name]}")
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error, "Could not remove policy module: #{detail}";
+ end
+
+ def exists?
+ self.debug "Checking for module #{@resource[:name]}"
+ execpipe("#{command(:semodule)} --list") do |out|
+ out.each do |line|
+ if line =~ /#{@resource[:name]}\b/
+ return :true
end
- nil
+ end
end
+ nil
+ end
- def syncversion
- self.debug "Checking syncversion on #{@resource[:name]}"
+ def syncversion
+ self.debug "Checking syncversion on #{@resource[:name]}"
- loadver = selmodversion_loaded
+ loadver = selmodversion_loaded
- if(loadver) then
- filever = selmodversion_file
- if (filever == loadver)
- return :true
- end
- end
- :false
+ if(loadver) then
+ filever = selmodversion_file
+ if (filever == loadver)
+ return :true
+ end
end
-
- def syncversion= (dosync)
- execoutput("#{command(:semodule)} --upgrade #{selmod_name_to_filename}")
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not upgrade policy module: #{detail}";
+ :false
+ end
+
+ def syncversion= (dosync)
+ execoutput("#{command(:semodule)} --upgrade #{selmod_name_to_filename}")
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error, "Could not upgrade policy module: #{detail}";
+ end
+
+ # Helper functions
+
+ def execoutput (cmd)
+ output = ''
+ begin
+ execpipe(cmd) do |out|
+ output = out.readlines.join('').chomp!
+ end
+ rescue Puppet::ExecutionFailure
+ raise Puppet::ExecutionFailure, output.split("\n")[0]
end
-
- # Helper functions
-
- def execoutput (cmd)
- output = ''
- begin
- execpipe(cmd) do |out|
- output = out.readlines.join('').chomp!
- end
- rescue Puppet::ExecutionFailure
- raise Puppet::ExecutionFailure, output.split("\n")[0]
- end
- output
+ output
+ end
+
+ def selmod_name_to_filename
+ if @resource[:selmodulepath]
+ return @resource[:selmodulepath]
+ else
+ return "#{@resource[:selmoduledir]}/#{@resource[:name]}.pp"
end
+ end
- def selmod_name_to_filename
- if @resource[:selmodulepath]
- return @resource[:selmodulepath]
- else
- return "#{@resource[:selmoduledir]}/#{@resource[:name]}.pp"
- end
- end
+ def selmod_readnext (handle)
+ len = handle.read(4).unpack('L')[0]
+ handle.read(len)
+ end
- def selmod_readnext (handle)
- len = handle.read(4).unpack('L')[0]
- handle.read(len)
- end
-
- def selmodversion_file
- magic = 0xF97CFF8F
+ def selmodversion_file
+ magic = 0xF97CFF8F
- filename = selmod_name_to_filename
- mod = File.new(filename, "r")
+ filename = selmod_name_to_filename
+ mod = File.new(filename, "r")
- (hdr, ver, numsec) = mod.read(12).unpack('LLL')
+ (hdr, ver, numsec) = mod.read(12).unpack('LLL')
- raise Puppet::Error, "Found #{hdr} instead of magic #{magic} in #{filename}" if hdr != magic
+ raise Puppet::Error, "Found #{hdr} instead of magic #{magic} in #{filename}" if hdr != magic
- raise Puppet::Error, "Unknown policy file version #{ver} in #{filename}" if ver != 1
+ raise Puppet::Error, "Unknown policy file version #{ver} in #{filename}" if ver != 1
- # Read through (and throw away) the file section offsets, and also
- # the magic header for the first section.
+ # Read through (and throw away) the file section offsets, and also
+ # the magic header for the first section.
- mod.read((numsec + 1) * 4)
+ mod.read((numsec + 1) * 4)
- ## Section 1 should be "SE Linux Module"
+ ## Section 1 should be "SE Linux Module"
- selmod_readnext(mod)
- selmod_readnext(mod)
+ selmod_readnext(mod)
+ selmod_readnext(mod)
- # Skip past the section headers
- mod.read(14)
+ # Skip past the section headers
+ mod.read(14)
- # Module name
- selmod_readnext(mod)
+ # Module name
+ selmod_readnext(mod)
- # At last! the version
+ # At last! the version
- v = selmod_readnext(mod)
+ v = selmod_readnext(mod)
- self.debug "file version #{v}"
- v
- end
+ self.debug "file version #{v}"
+ v
+ end
- def selmodversion_loaded
- lines = ()
- begin
- execpipe("#{command(:semodule)} --list") do |output|
- lines = output.readlines
- lines.each do |line|
- line.chomp!
- bits = line.split
- if bits[0] == @resource[:name]
- self.debug "load version #{bits[1]}"
- return bits[1]
- end
- end
- end
- rescue Puppet::ExecutionFailure
- raise Puppet::ExecutionFailure, "Could not list policy modules: #{lines.join(' ').chomp!}"
+ def selmodversion_loaded
+ lines = ()
+ begin
+ execpipe("#{command(:semodule)} --list") do |output|
+ lines = output.readlines
+ lines.each do |line|
+ line.chomp!
+ bits = line.split
+ if bits[0] == @resource[:name]
+ self.debug "load version #{bits[1]}"
+ return bits[1]
+ end
end
- nil
+ end
+ rescue Puppet::ExecutionFailure
+ raise Puppet::ExecutionFailure, "Could not list policy modules: #{lines.join(' ').chomp!}"
end
+ nil
+ end
end
diff --git a/lib/puppet/provider/service/base.rb b/lib/puppet/provider/service/base.rb
index 50e8790d1..70d764187 100755
--- a/lib/puppet/provider/service/base.rb
+++ b/lib/puppet/provider/service/base.rb
@@ -1,144 +1,144 @@
Puppet::Type.type(:service).provide :base do
- desc "The simplest form of service support.
-
- You have to specify enough about your service for this to work; the
- minimum you can specify is a binary for starting the process, and this
- same binary will be searched for in the process table to stop the
- service. It is preferable to specify start, stop, and status commands,
- akin to how you would do so using ``init``.
-
- "
-
- commands :kill => "kill"
-
- def self.instances
- []
- end
-
- # Get the process ID for a running process. Requires the 'pattern'
- # parameter.
- def getpid
- @resource.fail "Either stop/status commands or a pattern must be specified" unless @resource[:pattern]
- ps = Facter["ps"].value
- @resource.fail "You must upgrade Facter to a version that includes 'ps'" unless ps and ps != ""
- regex = Regexp.new(@resource[:pattern])
- self.debug "Executing '#{ps}'"
- IO.popen(ps) { |table|
- table.each { |line|
- if regex.match(line)
- ary = line.sub(/^\s+/, '').split(/\s+/)
- return ary[1]
- end
- }
- }
-
- nil
- end
-
- # How to restart the process.
- def restart
- if @resource[:restart] or restartcmd
- ucommand(:restart)
- else
- self.stop
- self.start
- end
- end
-
- # There is no default command, which causes other methods to be used
- def restartcmd
- end
-
- # Check if the process is running. Prefer the 'status' parameter,
- # then 'statuscmd' method, then look in the process table. We give
- # the object the option to not return a status command, which might
- # happen if, for instance, it has an init script (and thus responds to
- # 'statuscmd') but does not have 'hasstatus' enabled.
- def status
- if @resource[:status] or statuscmd
- # Don't fail when the exit status is not 0.
- ucommand(:status, false)
-
- # Expicitly calling exitstatus to facilitate testing
- if $CHILD_STATUS.exitstatus == 0
- return :running
- else
- return :stopped
- end
- elsif pid = self.getpid
- self.debug "PID is #{pid}"
- return :running
- else
- return :stopped
+ desc "The simplest form of service support.
+
+ You have to specify enough about your service for this to work; the
+ minimum you can specify is a binary for starting the process, and this
+ same binary will be searched for in the process table to stop the
+ service. It is preferable to specify start, stop, and status commands,
+ akin to how you would do so using ``init``.
+
+ "
+
+ commands :kill => "kill"
+
+ def self.instances
+ []
+ end
+
+ # Get the process ID for a running process. Requires the 'pattern'
+ # parameter.
+ def getpid
+ @resource.fail "Either stop/status commands or a pattern must be specified" unless @resource[:pattern]
+ ps = Facter["ps"].value
+ @resource.fail "You must upgrade Facter to a version that includes 'ps'" unless ps and ps != ""
+ regex = Regexp.new(@resource[:pattern])
+ self.debug "Executing '#{ps}'"
+ IO.popen(ps) { |table|
+ table.each { |line|
+ if regex.match(line)
+ ary = line.sub(/^\s+/, '').split(/\s+/)
+ return ary[1]
end
+ }
+ }
+
+ nil
+ end
+
+ # How to restart the process.
+ def restart
+ if @resource[:restart] or restartcmd
+ ucommand(:restart)
+ else
+ self.stop
+ self.start
end
-
- # There is no default command, which causes other methods to be used
- def statuscmd
+ end
+
+ # There is no default command, which causes other methods to be used
+ def restartcmd
+ end
+
+ # Check if the process is running. Prefer the 'status' parameter,
+ # then 'statuscmd' method, then look in the process table. We give
+ # the object the option to not return a status command, which might
+ # happen if, for instance, it has an init script (and thus responds to
+ # 'statuscmd') but does not have 'hasstatus' enabled.
+ def status
+ if @resource[:status] or statuscmd
+ # Don't fail when the exit status is not 0.
+ ucommand(:status, false)
+
+ # Expicitly calling exitstatus to facilitate testing
+ if $CHILD_STATUS.exitstatus == 0
+ return :running
+ else
+ return :stopped
+ end
+ elsif pid = self.getpid
+ self.debug "PID is #{pid}"
+ return :running
+ else
+ return :stopped
end
-
- # Run the 'start' parameter command, or the specified 'startcmd'.
- def start
- ucommand(:start)
+ end
+
+ # There is no default command, which causes other methods to be used
+ def statuscmd
+ end
+
+ # Run the 'start' parameter command, or the specified 'startcmd'.
+ def start
+ ucommand(:start)
+ end
+
+ # The command used to start. Generated if the 'binary' argument
+ # is passed.
+ def startcmd
+ if @resource[:binary]
+ return @resource[:binary]
+ else
+ raise Puppet::Error,
+ "Services must specify a start command or a binary"
end
-
- # The command used to start. Generated if the 'binary' argument
- # is passed.
- def startcmd
- if @resource[:binary]
- return @resource[:binary]
- else
- raise Puppet::Error,
- "Services must specify a start command or a binary"
- end
+ end
+
+ # Stop the service. If a 'stop' parameter is specified, it
+ # takes precedence; otherwise checks if the object responds to
+ # a 'stopcmd' method, and if so runs that; otherwise, looks
+ # for the process in the process table.
+ # This method will generally not be overridden by submodules.
+ def stop
+ if @resource[:stop] or stopcmd
+ ucommand(:stop)
+ else
+ pid = getpid
+ unless pid
+ self.info "#{self.name} is not running"
+ return false
+ end
+ begin
+ output = kill pid
+ rescue Puppet::ExecutionFailure => detail
+ @resource.fail "Could not kill #{self.name}, PID #{pid}: #{output}"
+ end
+ return true
end
-
- # Stop the service. If a 'stop' parameter is specified, it
- # takes precedence; otherwise checks if the object responds to
- # a 'stopcmd' method, and if so runs that; otherwise, looks
- # for the process in the process table.
- # This method will generally not be overridden by submodules.
- def stop
- if @resource[:stop] or stopcmd
- ucommand(:stop)
- else
- pid = getpid
- unless pid
- self.info "#{self.name} is not running"
- return false
- end
- begin
- output = kill pid
- rescue Puppet::ExecutionFailure => detail
- @resource.fail "Could not kill #{self.name}, PID #{pid}: #{output}"
- end
- return true
- end
+ end
+
+ # There is no default command, which causes other methods to be used
+ def stopcmd
+ end
+
+ # A simple wrapper so execution failures are a bit more informative.
+ def texecute(type, command, fof = true)
+ begin
+ # #565: Services generally produce no output, so squelch them.
+ execute(command, :failonfail => fof, :squelch => true)
+ rescue Puppet::ExecutionFailure => detail
+ @resource.fail "Could not #{type} #{@resource.ref}: #{detail}"
end
-
- # There is no default command, which causes other methods to be used
- def stopcmd
- end
-
- # A simple wrapper so execution failures are a bit more informative.
- def texecute(type, command, fof = true)
- begin
- # #565: Services generally produce no output, so squelch them.
- execute(command, :failonfail => fof, :squelch => true)
- rescue Puppet::ExecutionFailure => detail
- @resource.fail "Could not #{type} #{@resource.ref}: #{detail}"
- end
- nil
- end
-
- # Use either a specified command or the default for our provider.
- def ucommand(type, fof = true)
- if c = @resource[type]
- cmd = [c]
- else
- cmd = [send("#{type}cmd")].flatten
- end
- texecute(type, cmd, fof)
+ nil
+ end
+
+ # Use either a specified command or the default for our provider.
+ def ucommand(type, fof = true)
+ if c = @resource[type]
+ cmd = [c]
+ else
+ cmd = [send("#{type}cmd")].flatten
end
+ texecute(type, cmd, fof)
+ end
end
diff --git a/lib/puppet/provider/service/bsd.rb b/lib/puppet/provider/service/bsd.rb
index 15e4385a1..2e00c33f1 100644
--- a/lib/puppet/provider/service/bsd.rb
+++ b/lib/puppet/provider/service/bsd.rb
@@ -1,48 +1,48 @@
# Manage FreeBSD services.
Puppet::Type.type(:service).provide :bsd, :parent => :init do
- desc "FreeBSD's (and probably NetBSD?) form of ``init``-style service management.
+ desc "FreeBSD's (and probably NetBSD?) form of ``init``-style service management.
- Uses ``rc.conf.d`` for service enabling and disabling.
+ Uses ``rc.conf.d`` for service enabling and disabling.
"
- confine :operatingsystem => [:freebsd, :netbsd, :openbsd]
-
- @@rcconf_dir = '/etc/rc.conf.d'
-
- def self.defpath
- superclass.defpath
- end
-
- # remove service file from rc.conf.d to disable it
- def disable
- rcfile = File.join(@@rcconf_dir, @model[:name])
- File.delete(rcfile) if File.exists?(rcfile)
- end
-
- # if the service file exists in rc.conf.d then it's already enabled
- def enabled?
- rcfile = File.join(@@rcconf_dir, @model[:name])
- return :true if File.exists?(rcfile)
-
- :false
- end
-
- # enable service by creating a service file under rc.conf.d with the
- # proper contents
- def enable
- Dir.mkdir(@@rcconf_dir) if not File.exists?(@@rcconf_dir)
- rcfile = File.join(@@rcconf_dir, @model[:name])
- open(rcfile, 'w') { |f| f << "%s_enable=\"YES\"\n" % @model[:name] }
- end
-
- # Override stop/start commands to use one<cmd>'s and the avoid race condition
- # where provider trys to stop/start the service before it is enabled
- def startcmd
- [self.initscript, :onestart]
- end
-
- def stopcmd
- [self.initscript, :onestop]
- end
+ confine :operatingsystem => [:freebsd, :netbsd, :openbsd]
+
+ @@rcconf_dir = '/etc/rc.conf.d'
+
+ def self.defpath
+ superclass.defpath
+ end
+
+ # remove service file from rc.conf.d to disable it
+ def disable
+ rcfile = File.join(@@rcconf_dir, @model[:name])
+ File.delete(rcfile) if File.exists?(rcfile)
+ end
+
+ # if the service file exists in rc.conf.d then it's already enabled
+ def enabled?
+ rcfile = File.join(@@rcconf_dir, @model[:name])
+ return :true if File.exists?(rcfile)
+
+ :false
+ end
+
+ # enable service by creating a service file under rc.conf.d with the
+ # proper contents
+ def enable
+ Dir.mkdir(@@rcconf_dir) if not File.exists?(@@rcconf_dir)
+ rcfile = File.join(@@rcconf_dir, @model[:name])
+ open(rcfile, 'w') { |f| f << "%s_enable=\"YES\"\n" % @model[:name] }
+ end
+
+ # Override stop/start commands to use one<cmd>'s and the avoid race condition
+ # where provider trys to stop/start the service before it is enabled
+ def startcmd
+ [self.initscript, :onestart]
+ end
+
+ def stopcmd
+ [self.initscript, :onestop]
+ end
end
diff --git a/lib/puppet/provider/service/daemontools.rb b/lib/puppet/provider/service/daemontools.rb
index 7a584a1f9..65abf7728 100644
--- a/lib/puppet/provider/service/daemontools.rb
+++ b/lib/puppet/provider/service/daemontools.rb
@@ -2,193 +2,193 @@
#
# author Brice Figureau <brice-puppet@daysofwonder.com>
Puppet::Type.type(:service).provide :daemontools, :parent => :base do
- desc "Daemontools service management.
+ desc "Daemontools service management.
- This provider manages daemons running supervised by D.J.Bernstein daemontools.
- It tries to detect the service directory, with by order of preference:
+ This provider manages daemons running supervised by D.J.Bernstein daemontools.
+ It tries to detect the service directory, with by order of preference:
- * /service
- * /etc/service
- * /var/lib/svscan
+ * /service
+ * /etc/service
+ * /var/lib/svscan
- The daemon directory should be placed in a directory that can be
- by default in:
+ The daemon directory should be placed in a directory that can be
+ by default in:
- * /var/lib/service
- * /etc
+ * /var/lib/service
+ * /etc
- or this can be overriden in the service resource parameters::
+ or this can be overriden in the service resource parameters::
- service {
- \"myservice\":
- provider => \"daemontools\", path => \"/path/to/daemons\";
- }
+ service {
+ \"myservice\":
+ provider => \"daemontools\", path => \"/path/to/daemons\";
+ }
- This provider supports out of the box:
+ This provider supports out of the box:
- * start/stop (mapped to enable/disable)
- * enable/disable
- * restart
- * status
+ * start/stop (mapped to enable/disable)
+ * enable/disable
+ * restart
+ * status
- If a service has ensure => \"running\", it will link /path/to/daemon to
- /path/to/service, which will automatically enable the service.
+ If a service has ensure => \"running\", it will link /path/to/daemon to
+ /path/to/service, which will automatically enable the service.
- If a service has ensure => \"stopped\", it will only down the service, not
- remove the /path/to/service link.
+ If a service has ensure => \"stopped\", it will only down the service, not
+ remove the /path/to/service link.
- "
+ "
- commands :svc => "/usr/bin/svc", :svstat => "/usr/bin/svstat"
+ commands :svc => "/usr/bin/svc", :svstat => "/usr/bin/svstat"
- class << self
- attr_writer :defpath
+ class << self
+ attr_writer :defpath
- # Determine the daemon path.
- def defpath(dummy_argument=:work_arround_for_ruby_GC_bug)
- unless @defpath
- ["/var/lib/service", "/etc"].each do |path|
- if FileTest.exist?(path)
- @defpath = path
- break
- end
- end
- raise "Could not find the daemon directory (tested [/var/lib/service,/etc])" unless @defpath
- end
- @defpath
+ # Determine the daemon path.
+ def defpath(dummy_argument=:work_arround_for_ruby_GC_bug)
+ unless @defpath
+ ["/var/lib/service", "/etc"].each do |path|
+ if FileTest.exist?(path)
+ @defpath = path
+ break
+ end
end
+ raise "Could not find the daemon directory (tested [/var/lib/service,/etc])" unless @defpath
+ end
+ @defpath
end
+ end
- attr_writer :servicedir
+ attr_writer :servicedir
- # returns all providers for all existing services in @defpath
- # ie enabled or not
- def self.instances
- path = self.defpath
- unless FileTest.directory?(path)
- Puppet.notice "Service path #{path} does not exist"
- next
- end
-
- # reject entries that aren't either a directory
- # or don't contain a run file
- Dir.entries(path).reject { |e|
- fullpath = File.join(path, e)
- e =~ /^\./ or ! FileTest.directory?(fullpath) or ! FileTest.exist?(File.join(fullpath,"run"))
- }.collect do |name|
- new(:name => name, :path => path)
- end
+ # returns all providers for all existing services in @defpath
+ # ie enabled or not
+ def self.instances
+ path = self.defpath
+ unless FileTest.directory?(path)
+ Puppet.notice "Service path #{path} does not exist"
+ next
end
- # returns the daemon dir on this node
- def self.daemondir
- self.defpath
+ # reject entries that aren't either a directory
+ # or don't contain a run file
+ Dir.entries(path).reject { |e|
+ fullpath = File.join(path, e)
+ e =~ /^\./ or ! FileTest.directory?(fullpath) or ! FileTest.exist?(File.join(fullpath,"run"))
+ }.collect do |name|
+ new(:name => name, :path => path)
end
-
- # find the service dir on this node
- def servicedir
- unless @servicedir
- ["/service", "/etc/service","/var/lib/svscan"].each do |path|
- if FileTest.exist?(path)
- @servicedir = path
- break
- end
- end
- raise "Could not find service directory" unless @servicedir
+ end
+
+ # returns the daemon dir on this node
+ def self.daemondir
+ self.defpath
+ end
+
+ # find the service dir on this node
+ def servicedir
+ unless @servicedir
+ ["/service", "/etc/service","/var/lib/svscan"].each do |path|
+ if FileTest.exist?(path)
+ @servicedir = path
+ break
end
- @servicedir
+ end
+ raise "Could not find service directory" unless @servicedir
end
-
- # returns the full path of this service when enabled
- # (ie in the service directory)
- def service
- File.join(self.servicedir, resource[:name])
+ @servicedir
+ end
+
+ # returns the full path of this service when enabled
+ # (ie in the service directory)
+ def service
+ File.join(self.servicedir, resource[:name])
+ end
+
+ # returns the full path to the current daemon directory
+ # note that this path can be overriden in the resource
+ # definition
+ def daemon
+ File.join(resource[:path], resource[:name])
+ end
+
+ def status
+ begin
+ output = svstat self.service
+ if output =~ /:\s+up \(/
+ return :running
+ end
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error.new( "Could not get status for service #{resource.ref}: #{detail}" )
end
-
- # returns the full path to the current daemon directory
- # note that this path can be overriden in the resource
- # definition
- def daemon
- File.join(resource[:path], resource[:name])
+ :stopped
+ end
+
+ def setupservice
+ if resource[:manifest]
+ Puppet.notice "Configuring #{resource[:name]}"
+ command = [ resource[:manifest], resource[:name] ]
+ #texecute("setupservice", command)
+ rv = system("#{command}")
+ end
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error.new( "Cannot config #{self.service} to enable it: #{detail}" )
+ end
+
+ def enabled?
+ case self.status
+ when :running
+ # obviously if the daemon is running then it is enabled
+ return :true
+ else
+ # the service is enabled if it is linked
+ return FileTest.symlink?(self.service) ? :true : :false
end
-
- def status
- begin
- output = svstat self.service
- if output =~ /:\s+up \(/
- return :running
- end
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error.new( "Could not get status for service #{resource.ref}: #{detail}" )
+ end
+
+ def enable
+ if ! FileTest.directory?(self.daemon)
+ Puppet.notice "No daemon dir, calling setupservice for #{resource[:name]}"
+ self.setupservice
+ end
+ if self.daemon
+ if ! FileTest.symlink?(self.service)
+ Puppet.notice "Enabling #{self.service}: linking #{self.daemon} -> #{self.service}"
+ File.symlink(self.daemon, self.service)
end
- :stopped
- end
-
- def setupservice
- if resource[:manifest]
- Puppet.notice "Configuring #{resource[:name]}"
- command = [ resource[:manifest], resource[:name] ]
- #texecute("setupservice", command)
- rv = system("#{command}")
- end
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error.new( "Cannot config #{self.service} to enable it: #{detail}" )
- end
-
- def enabled?
- case self.status
- when :running
- # obviously if the daemon is running then it is enabled
- return :true
- else
- # the service is enabled if it is linked
- return FileTest.symlink?(self.service) ? :true : :false
+ end
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error.new( "No daemon directory found for #{self.service}")
+ end
+
+ def disable
+ begin
+ if ! FileTest.directory?(self.daemon)
+ Puppet.notice "No daemon dir, calling setupservice for #{resource[:name]}"
+ self.setupservice
+ end
+ if self.daemon
+ if FileTest.symlink?(self.service)
+ Puppet.notice "Disabling #{self.service}: removing link #{self.daemon} -> #{self.service}"
+ File.unlink(self.service)
end
- end
-
- def enable
- if ! FileTest.directory?(self.daemon)
- Puppet.notice "No daemon dir, calling setupservice for #{resource[:name]}"
- self.setupservice
- end
- if self.daemon
- if ! FileTest.symlink?(self.service)
- Puppet.notice "Enabling #{self.service}: linking #{self.daemon} -> #{self.service}"
- File.symlink(self.daemon, self.service)
- end
- end
+ end
rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error.new( "No daemon directory found for #{self.service}")
- end
-
- def disable
- begin
- if ! FileTest.directory?(self.daemon)
- Puppet.notice "No daemon dir, calling setupservice for #{resource[:name]}"
- self.setupservice
- end
- if self.daemon
- if FileTest.symlink?(self.service)
- Puppet.notice "Disabling #{self.service}: removing link #{self.daemon} -> #{self.service}"
- File.unlink(self.service)
- end
- end
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error.new( "No daemon directory found for #{self.service}")
- end
- self.stop
+ raise Puppet::Error.new( "No daemon directory found for #{self.service}")
end
+ self.stop
+ end
- def restart
- svc "-t", self.service
- end
+ def restart
+ svc "-t", self.service
+ end
- def start
- enable unless enabled? == :true
- svc "-u", self.service
- end
+ def start
+ enable unless enabled? == :true
+ svc "-u", self.service
+ end
- def stop
- svc "-d", self.service
- end
+ def stop
+ svc "-d", self.service
+ end
end
diff --git a/lib/puppet/provider/service/debian.rb b/lib/puppet/provider/service/debian.rb
index 746ed1ce3..4379f1b59 100755
--- a/lib/puppet/provider/service/debian.rb
+++ b/lib/puppet/provider/service/debian.rb
@@ -1,48 +1,48 @@
# Manage debian services. Start/stop is the same as InitSvc, but enable/disable
# is special.
Puppet::Type.type(:service).provide :debian, :parent => :init do
- desc "Debian's form of ``init``-style management.
-
- The only difference is that this supports service enabling and disabling
- via ``update-rc.d`` and determines enabled status via ``invoke-rc.d``.
-
- "
-
- commands :update_rc => "/usr/sbin/update-rc.d"
- # note this isn't being used as a command until
- # http://projects.reductivelabs.com/issues/2538
- # is resolved.
- commands :invoke_rc => "/usr/sbin/invoke-rc.d"
-
- defaultfor :operatingsystem => [:debian, :ubuntu]
-
- def self.defpath
- superclass.defpath
+ desc "Debian's form of ``init``-style management.
+
+ The only difference is that this supports service enabling and disabling
+ via ``update-rc.d`` and determines enabled status via ``invoke-rc.d``.
+
+ "
+
+ commands :update_rc => "/usr/sbin/update-rc.d"
+ # note this isn't being used as a command until
+ # http://projects.reductivelabs.com/issues/2538
+ # is resolved.
+ commands :invoke_rc => "/usr/sbin/invoke-rc.d"
+
+ defaultfor :operatingsystem => [:debian, :ubuntu]
+
+ def self.defpath
+ superclass.defpath
+ end
+
+ # Remove the symlinks
+ def disable
+ update_rc "-f", @resource[:name], "remove"
+ update_rc @resource[:name], "stop", "00", "1", "2", "3", "4", "5", "6", "."
+ end
+
+ def enabled?
+ # TODO: Replace system call when Puppet::Util.execute gives us a way
+ # to determine exit status. http://projects.reductivelabs.com/issues/2538
+ system("/usr/sbin/invoke-rc.d", "--quiet", "--query", @resource[:name], "start")
+
+ # 104 is the exit status when you query start an enabled service.
+ # 106 is the exit status when the policy layer supplies a fallback action
+ # See x-man-page://invoke-rc.d
+ if [104, 106].include?($CHILD_STATUS.exitstatus)
+ return :true
+ else
+ return :false
end
+ end
- # Remove the symlinks
- def disable
- update_rc "-f", @resource[:name], "remove"
- update_rc @resource[:name], "stop", "00", "1", "2", "3", "4", "5", "6", "."
- end
-
- def enabled?
- # TODO: Replace system call when Puppet::Util.execute gives us a way
- # to determine exit status. http://projects.reductivelabs.com/issues/2538
- system("/usr/sbin/invoke-rc.d", "--quiet", "--query", @resource[:name], "start")
-
- # 104 is the exit status when you query start an enabled service.
- # 106 is the exit status when the policy layer supplies a fallback action
- # See x-man-page://invoke-rc.d
- if [104, 106].include?($CHILD_STATUS.exitstatus)
- return :true
- else
- return :false
- end
- end
-
- def enable
- update_rc "-f", @resource[:name], "remove"
- update_rc @resource[:name], "defaults"
- end
+ def enable
+ update_rc "-f", @resource[:name], "remove"
+ update_rc @resource[:name], "defaults"
+ end
end
diff --git a/lib/puppet/provider/service/freebsd.rb b/lib/puppet/provider/service/freebsd.rb
index f491d70a2..10970e4da 100644
--- a/lib/puppet/provider/service/freebsd.rb
+++ b/lib/puppet/provider/service/freebsd.rb
@@ -1,136 +1,136 @@
Puppet::Type.type(:service).provide :freebsd, :parent => :init do
- desc "Provider for FreeBSD. Makes use of rcvar argument of init scripts and parses/edits rc files."
-
- confine :operatingsystem => [:freebsd]
- defaultfor :operatingsystem => [:freebsd]
-
- @@rcconf = '/etc/rc.conf'
- @@rcconf_local = '/etc/rc.conf.local'
- @@rcconf_dir = '/etc/rc.conf.d'
-
- def self.defpath
- superclass.defpath
- end
-
- # Executing an init script with the 'rcvar' argument returns
- # the service name, rcvar name and whether it's enabled/disabled
- def rcvar
- rcvar = execute([self.initscript, :rcvar], :failonfail => true, :squelch => false)
- rcvar = rcvar.split("\n")
- end
-
- # Extract service name
- def service_name
- name = self.rcvar[0]
- self.error("No service name found in rcvar") if name.nil?
- name = name.gsub!(/# (.*)/, '\1')
- self.error("Service name is empty") if name.nil?
- self.debug("Service name is #{name}")
- name
- end
-
- # Extract rcvar name
- def rcvar_name
- name = self.rcvar[1]
- self.error("No rcvar name found in rcvar") if name.nil?
- name = name.gsub!(/(.*)_enable=(.*)/, '\1')
- self.error("rcvar name is empty") if name.nil?
- self.debug("rcvar name is #{name}")
- name
- end
-
- # Extract rcvar value
- def rcvar_value
- value = self.rcvar[1]
- self.error("No rcvar value found in rcvar") if value.nil?
- value = value.gsub!(/(.*)_enable=\"?(.*)\"?/, '\2')
- self.error("rcvar value is empty") if value.nil?
- self.debug("rcvar value is #{value}")
- value
- end
-
- # Edit rc files and set the service to yes/no
- def rc_edit(yesno)
- service = self.service_name
- rcvar = self.rcvar_name
- self.debug("Editing rc files: setting #{rcvar} to #{yesno} for #{service}")
- self.rc_add(service, rcvar, yesno) if not self.rc_replace(service, rcvar, yesno)
- end
-
- # Try to find an existing setting in the rc files
- # and replace the value
- def rc_replace(service, rcvar, yesno)
- success = false
- # Replace in all files, not just in the first found with a match
- [@@rcconf, @@rcconf_local, @@rcconf_dir + "/#{service}"].each do |filename|
- if File.exists?(filename)
- s = File.read(filename)
- if s.gsub!(/(#{rcvar}_enable)=\"?(YES|NO)\"?/, "\\1=\"#{yesno}\"")
- File.open(filename, File::WRONLY) { |f| f << s }
- self.debug("Replaced in #{filename}")
- success = true
- end
- end
- end
- success
- end
-
- # Add a new setting to the rc files
- def rc_add(service, rcvar, yesno)
- append = "\n\# Added by Puppet\n#{rcvar}_enable=\"#{yesno}\""
- # First, try the one-file-per-service style
- if File.exists?(@@rcconf_dir)
- File.open(@@rcconf_dir + "/#{service}", File::WRONLY | File::APPEND | File::CREAT, 0644) {
- |f| f << append
- self.debug("Appended to #{f.path}")
- }
- else
- # Else, check the local rc file first, but don't create it
- if File.exists?(@@rcconf_local)
- File.open(@@rcconf_local, File::WRONLY | File::APPEND) {
- |f| f << append
- self.debug("Appended to #{f.path}")
- }
- else
- # At last use the standard rc.conf file
- File.open(@@rcconf, File::WRONLY | File::APPEND | File::CREAT, 0644) {
- |f| f << append
- self.debug("Appended to #{f.path}")
- }
- end
- end
- end
-
- def enabled?
- if /YES$/ =~ self.rcvar_value
- self.debug("Is enabled")
- return :true
+ desc "Provider for FreeBSD. Makes use of rcvar argument of init scripts and parses/edits rc files."
+
+ confine :operatingsystem => [:freebsd]
+ defaultfor :operatingsystem => [:freebsd]
+
+ @@rcconf = '/etc/rc.conf'
+ @@rcconf_local = '/etc/rc.conf.local'
+ @@rcconf_dir = '/etc/rc.conf.d'
+
+ def self.defpath
+ superclass.defpath
+ end
+
+ # Executing an init script with the 'rcvar' argument returns
+ # the service name, rcvar name and whether it's enabled/disabled
+ def rcvar
+ rcvar = execute([self.initscript, :rcvar], :failonfail => true, :squelch => false)
+ rcvar = rcvar.split("\n")
+ end
+
+ # Extract service name
+ def service_name
+ name = self.rcvar[0]
+ self.error("No service name found in rcvar") if name.nil?
+ name = name.gsub!(/# (.*)/, '\1')
+ self.error("Service name is empty") if name.nil?
+ self.debug("Service name is #{name}")
+ name
+ end
+
+ # Extract rcvar name
+ def rcvar_name
+ name = self.rcvar[1]
+ self.error("No rcvar name found in rcvar") if name.nil?
+ name = name.gsub!(/(.*)_enable=(.*)/, '\1')
+ self.error("rcvar name is empty") if name.nil?
+ self.debug("rcvar name is #{name}")
+ name
+ end
+
+ # Extract rcvar value
+ def rcvar_value
+ value = self.rcvar[1]
+ self.error("No rcvar value found in rcvar") if value.nil?
+ value = value.gsub!(/(.*)_enable=\"?(.*)\"?/, '\2')
+ self.error("rcvar value is empty") if value.nil?
+ self.debug("rcvar value is #{value}")
+ value
+ end
+
+ # Edit rc files and set the service to yes/no
+ def rc_edit(yesno)
+ service = self.service_name
+ rcvar = self.rcvar_name
+ self.debug("Editing rc files: setting #{rcvar} to #{yesno} for #{service}")
+ self.rc_add(service, rcvar, yesno) if not self.rc_replace(service, rcvar, yesno)
+ end
+
+ # Try to find an existing setting in the rc files
+ # and replace the value
+ def rc_replace(service, rcvar, yesno)
+ success = false
+ # Replace in all files, not just in the first found with a match
+ [@@rcconf, @@rcconf_local, @@rcconf_dir + "/#{service}"].each do |filename|
+ if File.exists?(filename)
+ s = File.read(filename)
+ if s.gsub!(/(#{rcvar}_enable)=\"?(YES|NO)\"?/, "\\1=\"#{yesno}\"")
+ File.open(filename, File::WRONLY) { |f| f << s }
+ self.debug("Replaced in #{filename}")
+ success = true
end
- self.debug("Is disabled")
- :false
+ end
end
-
- def enable
- self.debug("Enabling")
- self.rc_edit("YES")
- end
-
- def disable
- self.debug("Disabling")
- self.rc_edit("NO")
- end
-
- def startcmd
- [self.initscript, :onestart]
- end
-
- def stopcmd
- [self.initscript, :onestop]
+ success
+ end
+
+ # Add a new setting to the rc files
+ def rc_add(service, rcvar, yesno)
+ append = "\n\# Added by Puppet\n#{rcvar}_enable=\"#{yesno}\""
+ # First, try the one-file-per-service style
+ if File.exists?(@@rcconf_dir)
+ File.open(@@rcconf_dir + "/#{service}", File::WRONLY | File::APPEND | File::CREAT, 0644) {
+ |f| f << append
+ self.debug("Appended to #{f.path}")
+ }
+ else
+ # Else, check the local rc file first, but don't create it
+ if File.exists?(@@rcconf_local)
+ File.open(@@rcconf_local, File::WRONLY | File::APPEND) {
+ |f| f << append
+ self.debug("Appended to #{f.path}")
+ }
+ else
+ # At last use the standard rc.conf file
+ File.open(@@rcconf, File::WRONLY | File::APPEND | File::CREAT, 0644) {
+ |f| f << append
+ self.debug("Appended to #{f.path}")
+ }
+ end
end
+ end
- def statuscmd
- [self.initscript, :onestatus]
+ def enabled?
+ if /YES$/ =~ self.rcvar_value
+ self.debug("Is enabled")
+ return :true
end
+ self.debug("Is disabled")
+ :false
+ end
+
+ def enable
+ self.debug("Enabling")
+ self.rc_edit("YES")
+ end
+
+ def disable
+ self.debug("Disabling")
+ self.rc_edit("NO")
+ end
+
+ def startcmd
+ [self.initscript, :onestart]
+ end
+
+ def stopcmd
+ [self.initscript, :onestop]
+ end
+
+ def statuscmd
+ [self.initscript, :onestatus]
+ end
end
diff --git a/lib/puppet/provider/service/gentoo.rb b/lib/puppet/provider/service/gentoo.rb
index 109524bc0..08250a06a 100644
--- a/lib/puppet/provider/service/gentoo.rb
+++ b/lib/puppet/provider/service/gentoo.rb
@@ -1,52 +1,52 @@
# Manage gentoo services. Start/stop is the same as InitSvc, but enable/disable
# is special.
Puppet::Type.type(:service).provide :gentoo, :parent => :init do
- desc "Gentoo's form of ``init``-style service management.
+ desc "Gentoo's form of ``init``-style service management.
- Uses ``rc-update`` for service enabling and disabling.
+ Uses ``rc-update`` for service enabling and disabling.
- "
+ "
- commands :update => "/sbin/rc-update"
+ commands :update => "/sbin/rc-update"
- confine :operatingsystem => :gentoo
+ confine :operatingsystem => :gentoo
- defaultfor :operatingsystem => :gentoo
+ defaultfor :operatingsystem => :gentoo
- def self.defpath
- superclass.defpath
- end
+ def self.defpath
+ superclass.defpath
+ end
+
+ def disable
+ output = update :del, @resource[:name], :default
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error, "Could not disable #{self.name}: #{output}"
+ end
- def disable
- output = update :del, @resource[:name], :default
+ def enabled?
+ begin
+ output = update :show
rescue Puppet::ExecutionFailure
- raise Puppet::Error, "Could not disable #{self.name}: #{output}"
+ return :false
end
- def enabled?
- begin
- output = update :show
- rescue Puppet::ExecutionFailure
- return :false
- end
-
- line = output.split(/\n/).find { |l| l.include?(@resource[:name]) }
+ line = output.split(/\n/).find { |l| l.include?(@resource[:name]) }
- return :false unless line
+ return :false unless line
- # If it's enabled then it will print output showing service | runlevel
- if output =~ /^\s*#{@resource[:name]}\s*\|\s*(boot|default)/
- return :true
- else
- return :false
- end
+ # If it's enabled then it will print output showing service | runlevel
+ if output =~ /^\s*#{@resource[:name]}\s*\|\s*(boot|default)/
+ return :true
+ else
+ return :false
end
+ end
- def enable
- output = update :add, @resource[:name], :default
- rescue Puppet::ExecutionFailure
- raise Puppet::Error, "Could not enable #{self.name}: #{output}"
- end
+ def enable
+ output = update :add, @resource[:name], :default
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error, "Could not enable #{self.name}: #{output}"
+ end
end
# $Id $
diff --git a/lib/puppet/provider/service/init.rb b/lib/puppet/provider/service/init.rb
index 17d3bad36..6abff12db 100755
--- a/lib/puppet/provider/service/init.rb
+++ b/lib/puppet/provider/service/init.rb
@@ -1,141 +1,141 @@
# The standard init-based service type. Many other service types are
# customizations of this module.
Puppet::Type.type(:service).provide :init, :parent => :base do
- desc "Standard init service management.
+ desc "Standard init service management.
- This provider assumes that the init script has no ``status`` command,
- because so few scripts do, so you need to either provide a status
- command or specify via ``hasstatus`` that one already exists in the
- init script.
+ This provider assumes that the init script has no ``status`` command,
+ because so few scripts do, so you need to either provide a status
+ command or specify via ``hasstatus`` that one already exists in the
+ init script.
"
- class << self
- attr_accessor :defpath
+ class << self
+ attr_accessor :defpath
+ end
+
+ case Facter["operatingsystem"].value
+ when "FreeBSD"
+ @defpath = ["/etc/rc.d", "/usr/local/etc/rc.d"]
+ when "HP-UX"
+ @defpath = "/sbin/init.d"
+ else
+ @defpath = "/etc/init.d"
+ end
+
+ # We can't confine this here, because the init path can be overridden.
+ #confine :exists => @defpath
+
+ # List all services of this type.
+ def self.instances
+ get_services(self.defpath)
+ end
+
+ def self.get_services(defpath, exclude=[])
+ defpath = [defpath] unless defpath.is_a? Array
+ instances = []
+ defpath.each do |path|
+ unless FileTest.directory?(path)
+ Puppet.debug "Service path #{path} does not exist"
+ next
+ end
+
+ check = [:ensure]
+
+ check << :enable if public_method_defined? :enabled?
+
+ Dir.entries(path).each do |name|
+ fullpath = File.join(path, name)
+ next if name =~ /^\./
+ next if exclude.include? name
+ next if not FileTest.executable?(fullpath)
+ instances << new(:name => name, :path => path, :hasstatus => true)
+ end
end
-
- case Facter["operatingsystem"].value
- when "FreeBSD"
- @defpath = ["/etc/rc.d", "/usr/local/etc/rc.d"]
- when "HP-UX"
- @defpath = "/sbin/init.d"
+ instances
+ end
+
+ # Mark that our init script supports 'status' commands.
+ def hasstatus=(value)
+ case value
+ when true, "true"; @parameters[:hasstatus] = true
+ when false, "false"; @parameters[:hasstatus] = false
else
- @defpath = "/etc/init.d"
- end
-
- # We can't confine this here, because the init path can be overridden.
- #confine :exists => @defpath
-
- # List all services of this type.
- def self.instances
- get_services(self.defpath)
- end
-
- def self.get_services(defpath, exclude=[])
- defpath = [defpath] unless defpath.is_a? Array
- instances = []
- defpath.each do |path|
- unless FileTest.directory?(path)
- Puppet.debug "Service path #{path} does not exist"
- next
- end
-
- check = [:ensure]
-
- check << :enable if public_method_defined? :enabled?
-
- Dir.entries(path).each do |name|
- fullpath = File.join(path, name)
- next if name =~ /^\./
- next if exclude.include? name
- next if not FileTest.executable?(fullpath)
- instances << new(:name => name, :path => path, :hasstatus => true)
- end
- end
- instances
+ raise Puppet::Error, "Invalid 'hasstatus' value #{value.inspect}"
end
-
- # Mark that our init script supports 'status' commands.
- def hasstatus=(value)
- case value
- when true, "true"; @parameters[:hasstatus] = true
- when false, "false"; @parameters[:hasstatus] = false
+ end
+
+ # Where is our init script?
+ def initscript
+ @initscript ||= self.search(@resource[:name])
+ end
+
+ def paths
+ @paths ||= @resource[:path].find_all do |path|
+ if File.directory?(path)
+ true
+ else
+ if File.exist?(path) and ! File.directory?(path)
+ self.debug "Search path #{path} is not a directory"
else
- raise Puppet::Error, "Invalid 'hasstatus' value #{value.inspect}"
+ self.debug "Search path #{path} does not exist"
end
+ false
+ end
end
-
- # Where is our init script?
- def initscript
- @initscript ||= self.search(@resource[:name])
- end
-
- def paths
- @paths ||= @resource[:path].find_all do |path|
- if File.directory?(path)
- true
- else
- if File.exist?(path) and ! File.directory?(path)
- self.debug "Search path #{path} is not a directory"
- else
- self.debug "Search path #{path} does not exist"
- end
- false
- end
- end
- end
-
- def search(name)
- paths.each { |path|
- fqname = File.join(path,name)
- begin
- stat = File.stat(fqname)
- rescue
- # should probably rescue specific errors...
- self.debug("Could not find #{name} in #{path}")
- next
- end
-
- # if we've gotten this far, we found a valid script
- return fqname
- }
-
- paths.each { |path|
- fqname_sh = File.join(path,"#{name}.sh")
- begin
- stat = File.stat(fqname_sh)
- rescue
- # should probably rescue specific errors...
- self.debug("Could not find #{name}.sh in #{path}")
- next
- end
-
- # if we've gotten this far, we found a valid script
- return fqname_sh
- }
- raise Puppet::Error, "Could not find init script for '#{name}'"
- end
-
- # The start command is just the init scriptwith 'start'.
- def startcmd
- [initscript, :start]
- end
-
- # The stop command is just the init script with 'stop'.
- def stopcmd
- [initscript, :stop]
- end
-
- def restartcmd
- (@resource[:hasrestart] == :true) && [initscript, :restart]
- end
-
- # If it was specified that the init script has a 'status' command, then
- # we just return that; otherwise, we return false, which causes it to
- # fallback to other mechanisms.
- def statuscmd
- (@resource[:hasstatus] == :true) && [initscript, :status]
- end
+ end
+
+ def search(name)
+ paths.each { |path|
+ fqname = File.join(path,name)
+ begin
+ stat = File.stat(fqname)
+ rescue
+ # should probably rescue specific errors...
+ self.debug("Could not find #{name} in #{path}")
+ next
+ end
+
+ # if we've gotten this far, we found a valid script
+ return fqname
+ }
+
+ paths.each { |path|
+ fqname_sh = File.join(path,"#{name}.sh")
+ begin
+ stat = File.stat(fqname_sh)
+ rescue
+ # should probably rescue specific errors...
+ self.debug("Could not find #{name}.sh in #{path}")
+ next
+ end
+
+ # if we've gotten this far, we found a valid script
+ return fqname_sh
+ }
+ raise Puppet::Error, "Could not find init script for '#{name}'"
+ end
+
+ # The start command is just the init scriptwith 'start'.
+ def startcmd
+ [initscript, :start]
+ end
+
+ # The stop command is just the init script with 'stop'.
+ def stopcmd
+ [initscript, :stop]
+ end
+
+ def restartcmd
+ (@resource[:hasrestart] == :true) && [initscript, :restart]
+ end
+
+ # If it was specified that the init script has a 'status' command, then
+ # we just return that; otherwise, we return false, which causes it to
+ # fallback to other mechanisms.
+ def statuscmd
+ (@resource[:hasstatus] == :true) && [initscript, :status]
+ end
end
diff --git a/lib/puppet/provider/service/launchd.rb b/lib/puppet/provider/service/launchd.rb
index 9be961b09..970359539 100644
--- a/lib/puppet/provider/service/launchd.rb
+++ b/lib/puppet/provider/service/launchd.rb
@@ -1,256 +1,256 @@
require 'facter/util/plist'
Puppet::Type.type(:service).provide :launchd, :parent => :base do
- desc "launchd service management framework.
-
- This provider manages launchd jobs, the default service framework for
- Mac OS X, that has also been open sourced by Apple for possible use on
- other platforms.
-
- See:
- * http://developer.apple.com/macosx/launchd.html
- * http://launchd.macosforge.org/
-
- This provider reads plists out of the following directories:
- * /System/Library/LaunchDaemons
- * /System/Library/LaunchAgents
- * /Library/LaunchDaemons
- * /Library/LaunchAgents
-
- and builds up a list of services based upon each plists \"Label\" entry.
-
- This provider supports:
- * ensure => running/stopped,
- * enable => true/false
- * status
- * restart
-
- Here is how the Puppet states correspond to launchd states:
- * stopped => job unloaded
- * started => job loaded
- * enabled => 'Disable' removed from job plist file
- * disabled => 'Disable' added to job plist file
-
- Note that this allows you to do something launchctl can't do, which is to
- be in a state of \"stopped/enabled\ or \"running/disabled\".
-
- "
-
- commands :launchctl => "/bin/launchctl"
- commands :sw_vers => "/usr/bin/sw_vers"
-
- defaultfor :operatingsystem => :darwin
- confine :operatingsystem => :darwin
-
- has_feature :enableable
-
- Launchd_Paths = ["/Library/LaunchAgents",
- "/Library/LaunchDaemons",
- "/System/Library/LaunchAgents",
- "/System/Library/LaunchDaemons",]
-
- Launchd_Overrides = "/var/db/launchd.db/com.apple.launchd/overrides.plist"
-
-
- # returns a label => path map for either all jobs, or just a single
- # job if the label is specified
- def self.jobsearch(label=nil)
- label_to_path_map = {}
- Launchd_Paths.each do |path|
- if FileTest.exists?(path)
- Dir.entries(path).each do |f|
- next if f =~ /^\..*$/
- next if FileTest.directory?(f)
- fullpath = File.join(path, f)
- job = Plist::parse_xml(fullpath)
- if job and job.has_key?("Label")
- if job["Label"] == label
- return { label => fullpath }
- else
- label_to_path_map[job["Label"]] = fullpath
- end
- end
- end
+ desc "launchd service management framework.
+
+ This provider manages launchd jobs, the default service framework for
+ Mac OS X, that has also been open sourced by Apple for possible use on
+ other platforms.
+
+ See:
+ * http://developer.apple.com/macosx/launchd.html
+ * http://launchd.macosforge.org/
+
+ This provider reads plists out of the following directories:
+ * /System/Library/LaunchDaemons
+ * /System/Library/LaunchAgents
+ * /Library/LaunchDaemons
+ * /Library/LaunchAgents
+
+ and builds up a list of services based upon each plists \"Label\" entry.
+
+ This provider supports:
+ * ensure => running/stopped,
+ * enable => true/false
+ * status
+ * restart
+
+ Here is how the Puppet states correspond to launchd states:
+ * stopped => job unloaded
+ * started => job loaded
+ * enabled => 'Disable' removed from job plist file
+ * disabled => 'Disable' added to job plist file
+
+ Note that this allows you to do something launchctl can't do, which is to
+ be in a state of \"stopped/enabled\ or \"running/disabled\".
+
+ "
+
+ commands :launchctl => "/bin/launchctl"
+ commands :sw_vers => "/usr/bin/sw_vers"
+
+ defaultfor :operatingsystem => :darwin
+ confine :operatingsystem => :darwin
+
+ has_feature :enableable
+
+ Launchd_Paths = ["/Library/LaunchAgents",
+ "/Library/LaunchDaemons",
+ "/System/Library/LaunchAgents",
+ "/System/Library/LaunchDaemons",]
+
+ Launchd_Overrides = "/var/db/launchd.db/com.apple.launchd/overrides.plist"
+
+
+ # returns a label => path map for either all jobs, or just a single
+ # job if the label is specified
+ def self.jobsearch(label=nil)
+ label_to_path_map = {}
+ Launchd_Paths.each do |path|
+ if FileTest.exists?(path)
+ Dir.entries(path).each do |f|
+ next if f =~ /^\..*$/
+ next if FileTest.directory?(f)
+ fullpath = File.join(path, f)
+ job = Plist::parse_xml(fullpath)
+ if job and job.has_key?("Label")
+ if job["Label"] == label
+ return { label => fullpath }
+ else
+ label_to_path_map[job["Label"]] = fullpath
end
+ end
end
-
- # if we didn't find the job above and we should have, error.
- raise Puppet::Error.new("Unable to find launchd plist for job: #{label}") if label
- # if returning all jobs
- label_to_path_map
- end
-
-
- def self.instances
- jobs = self.jobsearch
- jobs.keys.collect do |job|
- new(:name => job, :provider => :launchd, :path => jobs[job])
- end
+ end
end
+ # if we didn't find the job above and we should have, error.
+ raise Puppet::Error.new("Unable to find launchd plist for job: #{label}") if label
+ # if returning all jobs
+ label_to_path_map
+ end
- def self.get_macosx_version_major
- return @macosx_version_major if defined?(@macosx_version_major)
- begin
- # Make sure we've loaded all of the facts
- Facter.loadfacts
- if Facter.value(:macosx_productversion_major)
- product_version_major = Facter.value(:macosx_productversion_major)
- else
- # TODO: remove this code chunk once we require Facter 1.5.5 or higher.
- Puppet.warning("DEPRECATION WARNING: Future versions of the launchd provider will require Facter 1.5.5 or newer.")
- product_version = Facter.value(:macosx_productversion)
- fail("Could not determine OS X version from Facter") if product_version.nil?
- product_version_major = product_version.scan(/(\d+)\.(\d+)./).join(".")
- end
- fail("#{product_version_major} is not supported by the launchd provider") if %w{10.0 10.1 10.2 10.3}.include?(product_version_major)
- @macosx_version_major = product_version_major
- return @macosx_version_major
- rescue Puppet::ExecutionFailure => detail
- fail("Could not determine OS X version: #{detail}")
- end
+ def self.instances
+ jobs = self.jobsearch
+ jobs.keys.collect do |job|
+ new(:name => job, :provider => :launchd, :path => jobs[job])
end
-
-
- # finds the path for a given label and returns the path and parsed plist
- # as an array of [path, plist]. Note plist is really a Hash here.
- def plist_from_label(label)
- job = self.class.jobsearch(label)
- job_path = job[label]
- job_plist = Plist::parse_xml(job_path)
- raise Puppet::Error.new("Unable to parse launchd plist at path: #{job_path}") if not job_plist
- [job_path, job_plist]
+ end
+
+
+ def self.get_macosx_version_major
+ return @macosx_version_major if defined?(@macosx_version_major)
+ begin
+ # Make sure we've loaded all of the facts
+ Facter.loadfacts
+
+ if Facter.value(:macosx_productversion_major)
+ product_version_major = Facter.value(:macosx_productversion_major)
+ else
+ # TODO: remove this code chunk once we require Facter 1.5.5 or higher.
+ Puppet.warning("DEPRECATION WARNING: Future versions of the launchd provider will require Facter 1.5.5 or newer.")
+ product_version = Facter.value(:macosx_productversion)
+ fail("Could not determine OS X version from Facter") if product_version.nil?
+ product_version_major = product_version.scan(/(\d+)\.(\d+)./).join(".")
+ end
+ fail("#{product_version_major} is not supported by the launchd provider") if %w{10.0 10.1 10.2 10.3}.include?(product_version_major)
+ @macosx_version_major = product_version_major
+ return @macosx_version_major
+ rescue Puppet::ExecutionFailure => detail
+ fail("Could not determine OS X version: #{detail}")
end
-
-
- def status
- # launchctl list <jobname> exits zero if the job is loaded
- # and non-zero if it isn't. Simple way to check... but is only
- # available on OS X 10.5 unfortunately, so we grab the whole list
- # and check if our resource is included. The output formats differ
- # between 10.4 and 10.5, thus the necessity for splitting
- begin
- output = launchctl :list
- raise Puppet::Error.new("launchctl list failed to return any data.") if output.nil?
- output.split("\n").each do |j|
- return :running if j.split(/\s/).last == resource[:name]
- end
- return :stopped
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new("Unable to determine status of #{resource[:name]}")
- end
+ end
+
+
+ # finds the path for a given label and returns the path and parsed plist
+ # as an array of [path, plist]. Note plist is really a Hash here.
+ def plist_from_label(label)
+ job = self.class.jobsearch(label)
+ job_path = job[label]
+ job_plist = Plist::parse_xml(job_path)
+ raise Puppet::Error.new("Unable to parse launchd plist at path: #{job_path}") if not job_plist
+ [job_path, job_plist]
+ end
+
+
+ def status
+ # launchctl list <jobname> exits zero if the job is loaded
+ # and non-zero if it isn't. Simple way to check... but is only
+ # available on OS X 10.5 unfortunately, so we grab the whole list
+ # and check if our resource is included. The output formats differ
+ # between 10.4 and 10.5, thus the necessity for splitting
+ begin
+ output = launchctl :list
+ raise Puppet::Error.new("launchctl list failed to return any data.") if output.nil?
+ output.split("\n").each do |j|
+ return :running if j.split(/\s/).last == resource[:name]
+ end
+ return :stopped
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new("Unable to determine status of #{resource[:name]}")
end
-
-
- # start the service. To get to a state of running/enabled, we need to
- # conditionally enable at load, then disable by modifying the plist file
- # directly.
- def start
- job_path, job_plist = plist_from_label(resource[:name])
- did_enable_job = false
- cmds = []
- cmds << :launchctl << :load
- if self.enabled? == :false # launchctl won't load disabled jobs
- cmds << "-w"
- did_enable_job = true
- end
- cmds << job_path
- begin
- execute(cmds)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new("Unable to start service: #{resource[:name]} at path: #{job_path}")
- end
- # As load -w clears the Disabled flag, we need to add it in after
- self.disable if did_enable_job and resource[:enable] == :false
+ end
+
+
+ # start the service. To get to a state of running/enabled, we need to
+ # conditionally enable at load, then disable by modifying the plist file
+ # directly.
+ def start
+ job_path, job_plist = plist_from_label(resource[:name])
+ did_enable_job = false
+ cmds = []
+ cmds << :launchctl << :load
+ if self.enabled? == :false # launchctl won't load disabled jobs
+ cmds << "-w"
+ did_enable_job = true
end
-
-
- def stop
- job_path, job_plist = plist_from_label(resource[:name])
- did_disable_job = false
- cmds = []
- cmds << :launchctl << :unload
- if self.enabled? == :true # keepalive jobs can't be stopped without disabling
- cmds << "-w"
- did_disable_job = true
- end
- cmds << job_path
- begin
- execute(cmds)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error.new("Unable to stop service: #{resource[:name]} at path: #{job_path}")
- end
- # As unload -w sets the Disabled flag, we need to add it in after
- self.enable if did_disable_job and resource[:enable] == :true
+ cmds << job_path
+ begin
+ execute(cmds)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new("Unable to start service: #{resource[:name]} at path: #{job_path}")
end
-
-
- # launchd jobs are enabled by default. They are only disabled if the key
- # "Disabled" is set to true, but it can also be set to false to enable it.
- # In 10.6, the Disabled key in the job plist is consulted, but only if there
- # is no entry in the global overrides plist.
- # We need to draw a distinction between undefined, true and false for both
- # locations where the Disabled flag can be defined.
- def enabled?
- job_plist_disabled = nil
- overrides_disabled = nil
-
- job_path, job_plist = plist_from_label(resource[:name])
- job_plist_disabled = job_plist["Disabled"] if job_plist.has_key?("Disabled")
-
- if self.class.get_macosx_version_major == "10.6":
- overrides = Plist::parse_xml(Launchd_Overrides)
-
- unless overrides.nil?
- if overrides.has_key?(resource[:name])
- overrides_disabled = overrides[resource[:name]]["Disabled"] if overrides[resource[:name]].has_key?("Disabled")
- end
- end
- end
-
- if overrides_disabled.nil?
- if job_plist_disabled.nil? or job_plist_disabled == false
- return :true
- end
- elsif overrides_disabled == false
- return :true
- end
- :false
+ # As load -w clears the Disabled flag, we need to add it in after
+ self.disable if did_enable_job and resource[:enable] == :false
+ end
+
+
+ def stop
+ job_path, job_plist = plist_from_label(resource[:name])
+ did_disable_job = false
+ cmds = []
+ cmds << :launchctl << :unload
+ if self.enabled? == :true # keepalive jobs can't be stopped without disabling
+ cmds << "-w"
+ did_disable_job = true
end
-
-
- # enable and disable are a bit hacky. We write out the plist with the appropriate value
- # rather than dealing with launchctl as it is unable to change the Disabled flag
- # without actually loading/unloading the job.
- # In 10.6 we need to write out a disabled key to the global overrides plist, in earlier
- # versions this is stored in the job plist itself.
- def enable
- if self.class.get_macosx_version_major == "10.6"
- overrides = Plist::parse_xml(Launchd_Overrides)
- overrides[resource[:name]] = { "Disabled" => false }
- Plist::Emit.save_plist(overrides, Launchd_Overrides)
- else
- job_path, job_plist = plist_from_label(resource[:name])
- if self.enabled? == :false
- job_plist.delete("Disabled")
- Plist::Emit.save_plist(job_plist, job_path)
- end
+ cmds << job_path
+ begin
+ execute(cmds)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error.new("Unable to stop service: #{resource[:name]} at path: #{job_path}")
+ end
+ # As unload -w sets the Disabled flag, we need to add it in after
+ self.enable if did_disable_job and resource[:enable] == :true
+ end
+
+
+ # launchd jobs are enabled by default. They are only disabled if the key
+ # "Disabled" is set to true, but it can also be set to false to enable it.
+ # In 10.6, the Disabled key in the job plist is consulted, but only if there
+ # is no entry in the global overrides plist.
+ # We need to draw a distinction between undefined, true and false for both
+ # locations where the Disabled flag can be defined.
+ def enabled?
+ job_plist_disabled = nil
+ overrides_disabled = nil
+
+ job_path, job_plist = plist_from_label(resource[:name])
+ job_plist_disabled = job_plist["Disabled"] if job_plist.has_key?("Disabled")
+
+ if self.class.get_macosx_version_major == "10.6":
+ overrides = Plist::parse_xml(Launchd_Overrides)
+
+ unless overrides.nil?
+ if overrides.has_key?(resource[:name])
+ overrides_disabled = overrides[resource[:name]]["Disabled"] if overrides[resource[:name]].has_key?("Disabled")
end
+ end
end
-
- def disable
- if self.class.get_macosx_version_major == "10.6"
- overrides = Plist::parse_xml(Launchd_Overrides)
- overrides[resource[:name]] = { "Disabled" => true }
- Plist::Emit.save_plist(overrides, Launchd_Overrides)
- else
- job_path, job_plist = plist_from_label(resource[:name])
- job_plist["Disabled"] = true
- Plist::Emit.save_plist(job_plist, job_path)
- end
+ if overrides_disabled.nil?
+ if job_plist_disabled.nil? or job_plist_disabled == false
+ return :true
+ end
+ elsif overrides_disabled == false
+ return :true
+ end
+ :false
+ end
+
+
+ # enable and disable are a bit hacky. We write out the plist with the appropriate value
+ # rather than dealing with launchctl as it is unable to change the Disabled flag
+ # without actually loading/unloading the job.
+ # In 10.6 we need to write out a disabled key to the global overrides plist, in earlier
+ # versions this is stored in the job plist itself.
+ def enable
+ if self.class.get_macosx_version_major == "10.6"
+ overrides = Plist::parse_xml(Launchd_Overrides)
+ overrides[resource[:name]] = { "Disabled" => false }
+ Plist::Emit.save_plist(overrides, Launchd_Overrides)
+ else
+ job_path, job_plist = plist_from_label(resource[:name])
+ if self.enabled? == :false
+ job_plist.delete("Disabled")
+ Plist::Emit.save_plist(job_plist, job_path)
+ end
+ end
+ end
+
+
+ def disable
+ if self.class.get_macosx_version_major == "10.6"
+ overrides = Plist::parse_xml(Launchd_Overrides)
+ overrides[resource[:name]] = { "Disabled" => true }
+ Plist::Emit.save_plist(overrides, Launchd_Overrides)
+ else
+ job_path, job_plist = plist_from_label(resource[:name])
+ job_plist["Disabled"] = true
+ Plist::Emit.save_plist(job_plist, job_path)
end
+ end
end
diff --git a/lib/puppet/provider/service/redhat.rb b/lib/puppet/provider/service/redhat.rb
index 3a25db3ac..3ca67d66f 100755
--- a/lib/puppet/provider/service/redhat.rb
+++ b/lib/puppet/provider/service/redhat.rb
@@ -1,76 +1,76 @@
# Manage Red Hat services. Start/stop uses /sbin/service and enable/disable uses chkconfig
Puppet::Type.type(:service).provide :redhat, :parent => :init, :source => :init do
- desc "Red Hat's (and probably many others) form of ``init``-style service management:
+ desc "Red Hat's (and probably many others) form of ``init``-style service management:
- Uses ``chkconfig`` for service enabling and disabling.
+ Uses ``chkconfig`` for service enabling and disabling.
- "
+ "
- commands :chkconfig => "/sbin/chkconfig", :service => "/sbin/service"
+ commands :chkconfig => "/sbin/chkconfig", :service => "/sbin/service"
- defaultfor :operatingsystem => [:redhat, :fedora, :suse, :centos, :sles, :oel, :ovm]
+ defaultfor :operatingsystem => [:redhat, :fedora, :suse, :centos, :sles, :oel, :ovm]
- def self.instances
- # this exclude list is all from /sbin/service (5.x), but I did not exclude kudzu
- self.get_services(['/etc/init.d'], ['functions', 'halt', 'killall', 'single', 'linuxconf'])
- end
-
- def self.defpath
- superclass.defpath
- end
-
- # Remove the symlinks
- def disable
- output = chkconfig(@resource[:name], :off)
- rescue Puppet::ExecutionFailure
- raise Puppet::Error, "Could not disable #{self.name}: #{output}"
- end
-
- def enabled?
- begin
- output = chkconfig(@resource[:name])
- rescue Puppet::ExecutionFailure
- return :false
- end
-
- # If it's disabled on SuSE, then it will print output showing "off"
- # at the end
- if output =~ /.* off$/
- return :false
- end
+ def self.instances
+ # this exclude list is all from /sbin/service (5.x), but I did not exclude kudzu
+ self.get_services(['/etc/init.d'], ['functions', 'halt', 'killall', 'single', 'linuxconf'])
+ end
- :true
- end
-
- # Don't support them specifying runlevels; always use the runlevels
- # in the init scripts.
- def enable
- output = chkconfig(@resource[:name], :on)
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not enable #{self.name}: #{detail}"
- end
-
- def initscript
- raise Puppet::Error, "Do not directly call the init script for '#{@resource[:name]}'; use 'service' instead"
- end
+ def self.defpath
+ superclass.defpath
+ end
- # use hasstatus=>true when its set for the provider.
- def statuscmd
- ((@resource.provider.get(:hasstatus) == true) || (@resource[:hasstatus] == :true)) && [command(:service), @resource[:name], "status"]
- end
+ # Remove the symlinks
+ def disable
+ output = chkconfig(@resource[:name], :off)
+ rescue Puppet::ExecutionFailure
+ raise Puppet::Error, "Could not disable #{self.name}: #{output}"
+ end
- def restartcmd
- (@resource[:hasrestart] == :true) && [command(:service), @resource[:name], "restart"]
+ def enabled?
+ begin
+ output = chkconfig(@resource[:name])
+ rescue Puppet::ExecutionFailure
+ return :false
end
- def startcmd
- [command(:service), @resource[:name], "start"]
+ # If it's disabled on SuSE, then it will print output showing "off"
+ # at the end
+ if output =~ /.* off$/
+ return :false
end
- def stopcmd
- [command(:service), @resource[:name], "stop"]
- end
+ :true
+ end
+
+ # Don't support them specifying runlevels; always use the runlevels
+ # in the init scripts.
+ def enable
+ output = chkconfig(@resource[:name], :on)
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error, "Could not enable #{self.name}: #{detail}"
+ end
+
+ def initscript
+ raise Puppet::Error, "Do not directly call the init script for '#{@resource[:name]}'; use 'service' instead"
+ end
+
+ # use hasstatus=>true when its set for the provider.
+ def statuscmd
+ ((@resource.provider.get(:hasstatus) == true) || (@resource[:hasstatus] == :true)) && [command(:service), @resource[:name], "status"]
+ end
+
+ def restartcmd
+ (@resource[:hasrestart] == :true) && [command(:service), @resource[:name], "restart"]
+ end
+
+ def startcmd
+ [command(:service), @resource[:name], "start"]
+ end
+
+ def stopcmd
+ [command(:service), @resource[:name], "stop"]
+ end
end
diff --git a/lib/puppet/provider/service/runit.rb b/lib/puppet/provider/service/runit.rb
index c2603c9d8..0315b9597 100644
--- a/lib/puppet/provider/service/runit.rb
+++ b/lib/puppet/provider/service/runit.rb
@@ -2,102 +2,102 @@
#
# author Brice Figureau <brice-puppet@daysofwonder.com>
Puppet::Type.type(:service).provide :runit, :parent => :daemontools do
- desc "Runit service management.
+ desc "Runit service management.
- This provider manages daemons running supervised by Runit.
- It tries to detect the service directory, with by order of preference:
+ This provider manages daemons running supervised by Runit.
+ It tries to detect the service directory, with by order of preference:
- * /service
- * /var/service
- * /etc/service
+ * /service
+ * /var/service
+ * /etc/service
- The daemon directory should be placed in a directory that can be
- by default in:
+ The daemon directory should be placed in a directory that can be
+ by default in:
- * /etc/sv
+ * /etc/sv
- or this can be overriden in the service resource parameters::
+ or this can be overriden in the service resource parameters::
- service {
- \"myservice\":
- provider => \"runit\", path => \"/path/to/daemons\";
- }
+ service {
+ \"myservice\":
+ provider => \"runit\", path => \"/path/to/daemons\";
+ }
- This provider supports out of the box:
+ This provider supports out of the box:
- * start/stop
- * enable/disable
- * restart
- * status
+ * start/stop
+ * enable/disable
+ * restart
+ * status
"
- commands :sv => "/usr/bin/sv"
-
- class << self
- # this is necessary to autodetect a valid resource
- # default path, since there is no standard for such directory.
- def defpath(dummy_argument=:work_arround_for_ruby_GC_bug)
- unless @defpath
- ["/etc/sv", "/var/lib/service"].each do |path|
- if FileTest.exist?(path)
- @defpath = path
- break
- end
- end
- raise "Could not find the daemon directory (tested [/var/lib/service,/etc])" unless @defpath
- end
- @defpath
+ commands :sv => "/usr/bin/sv"
+
+ class << self
+ # this is necessary to autodetect a valid resource
+ # default path, since there is no standard for such directory.
+ def defpath(dummy_argument=:work_arround_for_ruby_GC_bug)
+ unless @defpath
+ ["/etc/sv", "/var/lib/service"].each do |path|
+ if FileTest.exist?(path)
+ @defpath = path
+ break
+ end
end
+ raise "Could not find the daemon directory (tested [/var/lib/service,/etc])" unless @defpath
+ end
+ @defpath
end
-
- # find the service dir on this node
- def servicedir
- unless @servicedir
- ["/service", "/etc/service","/var/service"].each do |path|
- if FileTest.exist?(path)
- @servicedir = path
- break
- end
- end
- raise "Could not find service directory" unless @servicedir
- end
- @servicedir
- end
-
- def status
- begin
- output = sv "status", self.daemon
- return :running if output =~ /^run: /
- rescue Puppet::ExecutionFailure => detail
- unless detail.message =~ /(warning: |runsv not running$)/
- raise Puppet::Error.new( "Could not get status for service #{resource.ref}: #{detail}" )
- end
+ end
+
+ # find the service dir on this node
+ def servicedir
+ unless @servicedir
+ ["/service", "/etc/service","/var/service"].each do |path|
+ if FileTest.exist?(path)
+ @servicedir = path
+ break
end
- :stopped
- end
-
- def stop
- sv "stop", self.service
+ end
+ raise "Could not find service directory" unless @servicedir
end
-
- def start
- enable unless enabled? == :true
- sv "start", self.service
- end
-
- def restart
- sv "restart", self.service
- end
-
- # disable by removing the symlink so that runit
- # doesn't restart our service behind our back
- # note that runit doesn't need to perform a stop
- # before a disable
- def disable
- # unlink the daemon symlink to disable it
- File.unlink(self.service) if FileTest.symlink?(self.service)
+ @servicedir
+ end
+
+ def status
+ begin
+ output = sv "status", self.daemon
+ return :running if output =~ /^run: /
+ rescue Puppet::ExecutionFailure => detail
+ unless detail.message =~ /(warning: |runsv not running$)/
+ raise Puppet::Error.new( "Could not get status for service #{resource.ref}: #{detail}" )
+ end
end
+ :stopped
+ end
+
+ def stop
+ sv "stop", self.service
+ end
+
+ def start
+ enable unless enabled? == :true
+ sv "start", self.service
+ end
+
+ def restart
+ sv "restart", self.service
+ end
+
+ # disable by removing the symlink so that runit
+ # doesn't restart our service behind our back
+ # note that runit doesn't need to perform a stop
+ # before a disable
+ def disable
+ # unlink the daemon symlink to disable it
+ File.unlink(self.service) if FileTest.symlink?(self.service)
+ end
end
diff --git a/lib/puppet/provider/service/smf.rb b/lib/puppet/provider/service/smf.rb
index ca7af9449..3efb2eb37 100755
--- a/lib/puppet/provider/service/smf.rb
+++ b/lib/puppet/provider/service/smf.rb
@@ -1,103 +1,103 @@
# Solaris 10 SMF-style services.
Puppet::Type.type(:service).provide :smf, :parent => :base do
- desc "Support for Sun's new Service Management Framework.
+ desc "Support for Sun's new Service Management Framework.
- Starting a service is effectively equivalent to enabling it, so there is
- only support for starting and stopping services, which also enables and
- disables them, respectively.
+ Starting a service is effectively equivalent to enabling it, so there is
+ only support for starting and stopping services, which also enables and
+ disables them, respectively.
- By specifying manifest => \"/path/to/service.xml\", the SMF manifest will
- be imported if it does not exist.
+ By specifying manifest => \"/path/to/service.xml\", the SMF manifest will
+ be imported if it does not exist.
- "
+ "
- defaultfor :operatingsystem => :solaris
+ defaultfor :operatingsystem => :solaris
- confine :operatingsystem => :solaris
+ confine :operatingsystem => :solaris
- commands :adm => "/usr/sbin/svcadm", :svcs => "/usr/bin/svcs"
- commands :svccfg => "/usr/sbin/svccfg"
+ commands :adm => "/usr/sbin/svcadm", :svcs => "/usr/bin/svcs"
+ commands :svccfg => "/usr/sbin/svccfg"
- def setupservice
- if resource[:manifest]
- [command(:svcs), "-l", @resource[:name]]
- if $CHILD_STATUS.exitstatus == 1
- Puppet.notice "Importing #{@resource[:manifest]} for #{@resource[:name]}"
- svccfg :import, resource[:manifest]
- end
- end
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error.new( "Cannot config #{self.service} to enable it: #{detail}" )
- end
-
- def enable
- self.start
- end
-
- def enabled?
- case self.status
- when :running
- return :true
- else
- return :false
+ def setupservice
+ if resource[:manifest]
+ [command(:svcs), "-l", @resource[:name]]
+ if $CHILD_STATUS.exitstatus == 1
+ Puppet.notice "Importing #{@resource[:manifest]} for #{@resource[:name]}"
+ svccfg :import, resource[:manifest]
end
+ end
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error.new( "Cannot config #{self.service} to enable it: #{detail}" )
+ end
+
+ def enable
+ self.start
+ end
+
+ def enabled?
+ case self.status
+ when :running
+ return :true
+ else
+ return :false
end
-
- def disable
- self.stop
+ end
+
+ def disable
+ self.stop
+ end
+
+ def restartcmd
+ [command(:adm), :restart, @resource[:name]]
+ end
+
+ def startcmd
+ self.setupservice
+ case self.status
+ when :stopped
+ [command(:adm), :enable, @resource[:name]]
+ when :maintenance
+ [command(:adm), :clear, @resource[:name]]
end
+ end
- def restartcmd
- [command(:adm), :restart, @resource[:name]]
+ def status
+ if @resource[:status]
+ super
+ return
end
- def startcmd
- self.setupservice
- case self.status
- when :stopped
- [command(:adm), :enable, @resource[:name]]
- when :maintenance
- [command(:adm), :clear, @resource[:name]]
- end
+ begin
+ # get the current state and the next state, and if the next
+ # state is set (i.e. not "-") use it for state comparison
+ states = svcs("-H", "-o", "state,nstate", @resource[:name]).chomp.split
+ state = states[1] == "-" ? states[0] : states[1]
+ rescue Puppet::ExecutionFailure
+ info "Could not get status on service #{self.name}"
+ return :stopped
end
- def status
- if @resource[:status]
- super
- return
- end
-
- begin
- # get the current state and the next state, and if the next
- # state is set (i.e. not "-") use it for state comparison
- states = svcs("-H", "-o", "state,nstate", @resource[:name]).chomp.split
- state = states[1] == "-" ? states[0] : states[1]
- rescue Puppet::ExecutionFailure
- info "Could not get status on service #{self.name}"
- return :stopped
- end
-
- case state
- when "online"
- #self.warning "matched running #{line.inspect}"
- return :running
- when "offline", "disabled", "uninitialized"
- #self.warning "matched stopped #{line.inspect}"
- return :stopped
- when "maintenance"
- return :maintenance
- when "legacy_run"
- raise Puppet::Error,
- "Cannot manage legacy services through SMF"
- else
- raise Puppet::Error,
- "Unmanageable state '#{state}' on service #{self.name}"
- end
-
+ case state
+ when "online"
+ #self.warning "matched running #{line.inspect}"
+ return :running
+ when "offline", "disabled", "uninitialized"
+ #self.warning "matched stopped #{line.inspect}"
+ return :stopped
+ when "maintenance"
+ return :maintenance
+ when "legacy_run"
+ raise Puppet::Error,
+ "Cannot manage legacy services through SMF"
+ else
+ raise Puppet::Error,
+ "Unmanageable state '#{state}' on service #{self.name}"
end
- def stopcmd
- [command(:adm), :disable, @resource[:name]]
- end
+ end
+
+ def stopcmd
+ [command(:adm), :disable, @resource[:name]]
+ end
end
diff --git a/lib/puppet/provider/service/src.rb b/lib/puppet/provider/service/src.rb
index aed88d531..2bd643c0b 100755
--- a/lib/puppet/provider/service/src.rb
+++ b/lib/puppet/provider/service/src.rb
@@ -1,87 +1,87 @@
# AIX System Resource controller (SRC)
Puppet::Type.type(:service).provide :src, :parent => :base do
- desc "Support for AIX's System Resource controller.
-
- Services are started/stopped based on the stopsrc and startsrc
- commands, and some services can be refreshed with refresh command.
-
- * Enabling and disableing services is not supported, as it requires
- modifications to /etc/inittab.
-
- * Starting and stopping groups of subsystems is not yet supported
- "
-
- defaultfor :operatingsystem => :aix
- confine :operatingsystem => :aix
-
- commands :stopsrc => "/usr/bin/stopsrc"
- commands :startsrc => "/usr/bin/startsrc"
- commands :refresh => "/usr/bin/refresh"
- commands :lssrc => "/usr/bin/lssrc"
-
- has_feature :refreshable
-
- def startcmd
- [command(:startsrc), "-s", @resource[:name]]
- end
-
- def stopcmd
- [command(:stopsrc), "-s", @resource[:name]]
- end
-
- def restart
- execute([command(:lssrc), "-Ss", @resource[:name]]).each do |line|
- args = line.split(":")
-
- next unless args[0] == @resource[:name]
-
- # Subsystems with the -K flag can get refreshed (HUPed)
- # While subsystems with -S (signals) must be stopped/started
- method = args[11]
- do_refresh = case method
- when "-K" then :true
- when "-S" then :false
- else self.fail("Unknown service communication method #{method}")
- end
-
- begin
- if do_refresh == :true
- execute([command(:refresh), "-s", @resource[:name]])
- else
- self.stop
- self.start
- end
- return :true
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error.new("Unable to restart service #{@resource[:name]}, error was: #{detail}" )
- end
- end
- self.fail("No such service found")
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error.new("Cannot get status of #{@resource[:name]}, error was: #{detail}" )
- end
-
- def status
- execute([command(:lssrc), "-s", @resource[:name]]).each do |line|
- args = line.split
-
- # This is the header line
- next unless args[0] == @resource[:name]
-
- # PID is the 3rd field, but inoperative subsystems
- # skip this so split doesn't work right
- state = case args[-1]
- when "active" then :running
- when "inoperative" then :stopped
- end
- Puppet.debug("Service #{@resource[:name]} is #{args[-1]}")
- return state
- end
- self.fail("No such service found")
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error.new("Cannot get status of #{@resource[:name]}, error was: #{detail}" )
- end
+ desc "Support for AIX's System Resource controller.
+
+ Services are started/stopped based on the stopsrc and startsrc
+ commands, and some services can be refreshed with refresh command.
+
+ * Enabling and disableing services is not supported, as it requires
+ modifications to /etc/inittab.
+
+ * Starting and stopping groups of subsystems is not yet supported
+ "
+
+ defaultfor :operatingsystem => :aix
+ confine :operatingsystem => :aix
+
+ commands :stopsrc => "/usr/bin/stopsrc"
+ commands :startsrc => "/usr/bin/startsrc"
+ commands :refresh => "/usr/bin/refresh"
+ commands :lssrc => "/usr/bin/lssrc"
+
+ has_feature :refreshable
+
+ def startcmd
+ [command(:startsrc), "-s", @resource[:name]]
+ end
+
+ def stopcmd
+ [command(:stopsrc), "-s", @resource[:name]]
+ end
+
+ def restart
+ execute([command(:lssrc), "-Ss", @resource[:name]]).each do |line|
+ args = line.split(":")
+
+ next unless args[0] == @resource[:name]
+
+ # Subsystems with the -K flag can get refreshed (HUPed)
+ # While subsystems with -S (signals) must be stopped/started
+ method = args[11]
+ do_refresh = case method
+ when "-K" then :true
+ when "-S" then :false
+ else self.fail("Unknown service communication method #{method}")
+ end
+
+ begin
+ if do_refresh == :true
+ execute([command(:refresh), "-s", @resource[:name]])
+ else
+ self.stop
+ self.start
+ end
+ return :true
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error.new("Unable to restart service #{@resource[:name]}, error was: #{detail}" )
+ end
+ end
+ self.fail("No such service found")
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error.new("Cannot get status of #{@resource[:name]}, error was: #{detail}" )
+ end
+
+ def status
+ execute([command(:lssrc), "-s", @resource[:name]]).each do |line|
+ args = line.split
+
+ # This is the header line
+ next unless args[0] == @resource[:name]
+
+ # PID is the 3rd field, but inoperative subsystems
+ # skip this so split doesn't work right
+ state = case args[-1]
+ when "active" then :running
+ when "inoperative" then :stopped
+ end
+ Puppet.debug("Service #{@resource[:name]} is #{args[-1]}")
+ return state
+ end
+ self.fail("No such service found")
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error.new("Cannot get status of #{@resource[:name]}, error was: #{detail}" )
+ end
end
diff --git a/lib/puppet/provider/ssh_authorized_key/parsed.rb b/lib/puppet/provider/ssh_authorized_key/parsed.rb
index a9738e761..82f6b8881 100644
--- a/lib/puppet/provider/ssh_authorized_key/parsed.rb
+++ b/lib/puppet/provider/ssh_authorized_key/parsed.rb
@@ -1,89 +1,89 @@
require 'puppet/provider/parsedfile'
- Puppet::Type.type(:ssh_authorized_key).provide(
- :parsed,
- :parent => Puppet::Provider::ParsedFile,
- :filetype => :flat,
+ Puppet::Type.type(:ssh_authorized_key).provide(
+ :parsed,
+ :parent => Puppet::Provider::ParsedFile,
+ :filetype => :flat,
- :default_target => ''
+ :default_target => ''
) do
- desc "Parse and generate authorized_keys files for SSH."
+ desc "Parse and generate authorized_keys files for SSH."
- text_line :comment, :match => /^#/
- text_line :blank, :match => /^\s+/
+ text_line :comment, :match => /^#/
+ text_line :blank, :match => /^\s+/
- record_line :parsed,
- :fields => %w{options type key name},
- :optional => %w{options},
- :rts => /^\s+/,
- :match => /^(?:(.+) )?(ssh-dss|ssh-rsa) ([^ ]+) ?(.*)$/,
- :post_parse => proc { |h|
- h[:name] = "" if h[:name] == :absent
- h[:options] ||= [:absent]
- h[:options] = Puppet::Type::Ssh_authorized_key::ProviderParsed.parse_options(h[:options]) if h[:options].is_a? String
- },
- :pre_gen => proc { |h|
- h[:options] = [] if h[:options].include?(:absent)
- h[:options] = h[:options].join(',')
- }
+ record_line :parsed,
+ :fields => %w{options type key name},
+ :optional => %w{options},
+ :rts => /^\s+/,
+ :match => /^(?:(.+) )?(ssh-dss|ssh-rsa) ([^ ]+) ?(.*)$/,
+ :post_parse => proc { |h|
+ h[:name] = "" if h[:name] == :absent
+ h[:options] ||= [:absent]
+ h[:options] = Puppet::Type::Ssh_authorized_key::ProviderParsed.parse_options(h[:options]) if h[:options].is_a? String
+ },
+ :pre_gen => proc { |h|
+ h[:options] = [] if h[:options].include?(:absent)
+ h[:options] = h[:options].join(',')
+ }
- record_line :key_v1,
- :fields => %w{options bits exponent modulus name},
- :optional => %w{options},
- :rts => /^\s+/,
- :match => /^(?:(.+) )?(\d+) (\d+) (\d+)(?: (.+))?$/
+ record_line :key_v1,
+ :fields => %w{options bits exponent modulus name},
+ :optional => %w{options},
+ :rts => /^\s+/,
+ :match => /^(?:(.+) )?(\d+) (\d+) (\d+)(?: (.+))?$/
- def dir_perm
- 0700
- end
+ def dir_perm
+ 0700
+ end
- def file_perm
- 0600
- end
+ def file_perm
+ 0600
+ end
- def target
- @resource.should(:target) || File.expand_path("~#{@resource.should(:user)}/.ssh/authorized_keys")
- rescue
- raise Puppet::Error, "Target not defined and/or specified user does not exist yet"
- end
+ def target
+ @resource.should(:target) || File.expand_path("~#{@resource.should(:user)}/.ssh/authorized_keys")
+ rescue
+ raise Puppet::Error, "Target not defined and/or specified user does not exist yet"
+ end
- def user
- uid = File.stat(target).uid
- Etc.getpwuid(uid).name
- end
+ def user
+ uid = File.stat(target).uid
+ Etc.getpwuid(uid).name
+ end
- def flush
- raise Puppet::Error, "Cannot write SSH authorized keys without user" unless @resource.should(:user)
- raise Puppet::Error, "User '#{@resource.should(:user)}' does not exist" unless uid = Puppet::Util.uid(@resource.should(:user))
- unless File.exist?(dir = File.dirname(target))
- Puppet.debug "Creating #{dir}"
- Dir.mkdir(dir, dir_perm)
- File.chown(uid, nil, dir)
- end
- Puppet::Util::SUIDManager.asuser(@resource.should(:user)) { super }
- File.chown(uid, nil, target)
- File.chmod(file_perm, target)
+ def flush
+ raise Puppet::Error, "Cannot write SSH authorized keys without user" unless @resource.should(:user)
+ raise Puppet::Error, "User '#{@resource.should(:user)}' does not exist" unless uid = Puppet::Util.uid(@resource.should(:user))
+ unless File.exist?(dir = File.dirname(target))
+ Puppet.debug "Creating #{dir}"
+ Dir.mkdir(dir, dir_perm)
+ File.chown(uid, nil, dir)
end
+ Puppet::Util::SUIDManager.asuser(@resource.should(:user)) { super }
+ File.chown(uid, nil, target)
+ File.chmod(file_perm, target)
+ end
- # parse sshv2 option strings, wich is a comma separated list of
- # either key="values" elements or bare-word elements
- def self.parse_options(options)
- result = []
- scanner = StringScanner.new(options)
- while !scanner.eos?
- scanner.skip(/[ \t]*/)
- # scan a long option
- if out = scanner.scan(/[-a-z0-9A-Z_]+=\".*?\"/) or out = scanner.scan(/[-a-z0-9A-Z_]+/)
- result << out
- else
- # found an unscannable token, let's abort
- break
- end
- # eat a comma
- scanner.skip(/[ \t]*,[ \t]*/)
- end
- result
+ # parse sshv2 option strings, wich is a comma separated list of
+ # either key="values" elements or bare-word elements
+ def self.parse_options(options)
+ result = []
+ scanner = StringScanner.new(options)
+ while !scanner.eos?
+ scanner.skip(/[ \t]*/)
+ # scan a long option
+ if out = scanner.scan(/[-a-z0-9A-Z_]+=\".*?\"/) or out = scanner.scan(/[-a-z0-9A-Z_]+/)
+ result << out
+ else
+ # found an unscannable token, let's abort
+ break
+ end
+ # eat a comma
+ scanner.skip(/[ \t]*,[ \t]*/)
end
+ result
+ end
end
diff --git a/lib/puppet/provider/sshkey/parsed.rb b/lib/puppet/provider/sshkey/parsed.rb
index 4fefc4067..dcc55b403 100755
--- a/lib/puppet/provider/sshkey/parsed.rb
+++ b/lib/puppet/provider/sshkey/parsed.rb
@@ -4,35 +4,35 @@ known = nil
case Facter.value(:operatingsystem)
when "Darwin"; known = "/etc/ssh_known_hosts"
else
- known = "/etc/ssh/ssh_known_hosts"
+ known = "/etc/ssh/ssh_known_hosts"
end
- Puppet::Type.type(:sshkey).provide(
- :parsed,
- :parent => Puppet::Provider::ParsedFile,
- :default_target => known,
+ Puppet::Type.type(:sshkey).provide(
+ :parsed,
+ :parent => Puppet::Provider::ParsedFile,
+ :default_target => known,
- :filetype => :flat
+ :filetype => :flat
) do
- desc "Parse and generate host-wide known hosts files for SSH."
+ desc "Parse and generate host-wide known hosts files for SSH."
- text_line :comment, :match => /^#/
- text_line :blank, :match => /^\s+/
+ text_line :comment, :match => /^#/
+ text_line :blank, :match => /^\s+/
- record_line :parsed, :fields => %w{name type key},
- :post_parse => proc { |hash|
- names = hash[:name].split(",", -1)
- hash[:name] = names.shift
- hash[:host_aliases] = names
- },
- :pre_gen => proc { |hash|
- if hash[:host_aliases]
- names = [hash[:name], hash[:host_aliases]].flatten
+ record_line :parsed, :fields => %w{name type key},
+ :post_parse => proc { |hash|
+ names = hash[:name].split(",", -1)
+ hash[:name] = names.shift
+ hash[:host_aliases] = names
+ },
+ :pre_gen => proc { |hash|
+ if hash[:host_aliases]
+ names = [hash[:name], hash[:host_aliases]].flatten
- hash[:name] = [hash[:name], hash[:host_aliases]].flatten.join(",")
- hash.delete(:host_aliases)
- end
- }
+ hash[:name] = [hash[:name], hash[:host_aliases]].flatten.join(",")
+ hash.delete(:host_aliases)
+ end
+ }
end
diff --git a/lib/puppet/provider/user/directoryservice.rb b/lib/puppet/provider/user/directoryservice.rb
index 46d017e4b..4b62a6ae7 100644
--- a/lib/puppet/provider/user/directoryservice.rb
+++ b/lib/puppet/provider/user/directoryservice.rb
@@ -15,86 +15,86 @@
require 'puppet/provider/nameservice/directoryservice'
Puppet::Type.type(:user).provide :directoryservice, :parent => Puppet::Provider::NameService::DirectoryService do
- desc "User management using DirectoryService on OS X."
+ desc "User management using DirectoryService on OS X."
- commands :dscl => "/usr/bin/dscl"
- confine :operatingsystem => :darwin
- defaultfor :operatingsystem => :darwin
+ commands :dscl => "/usr/bin/dscl"
+ confine :operatingsystem => :darwin
+ defaultfor :operatingsystem => :darwin
- # JJM: DirectoryService can manage passwords.
- # This needs to be a special option to dscl though (-passwd)
- has_feature :manages_passwords
+ # JJM: DirectoryService can manage passwords.
+ # This needs to be a special option to dscl though (-passwd)
+ has_feature :manages_passwords
- # JJM: comment matches up with the /etc/passwd concept of an user
- options :comment, :key => "realname"
- options :password, :key => "passwd"
+ # JJM: comment matches up with the /etc/passwd concept of an user
+ options :comment, :key => "realname"
+ options :password, :key => "passwd"
- autogen_defaults :home => "/var/empty", :shell => "/usr/bin/false"
+ autogen_defaults :home => "/var/empty", :shell => "/usr/bin/false"
- verify :gid, "GID must be an integer" do |value|
- value.is_a? Integer
- end
+ verify :gid, "GID must be an integer" do |value|
+ value.is_a? Integer
+ end
- verify :uid, "UID must be an integer" do |value|
- value.is_a? Integer
- end
+ verify :uid, "UID must be an integer" do |value|
+ value.is_a? Integer
+ end
- def autogen_comment
- @resource[:name].capitalize
- end
+ def autogen_comment
+ @resource[:name].capitalize
+ end
- # The list of all groups the user is a member of.
- # JJM: FIXME: Override this method...
- def groups
- groups = []
- groups.join(",")
- end
+ # The list of all groups the user is a member of.
+ # JJM: FIXME: Override this method...
+ def groups
+ groups = []
+ groups.join(",")
+ end
- # This is really lame. We have to iterate over each
- # of the groups and add us to them.
- def groups=(groups)
- # case groups
- # when Fixnum
- # groups = [groups.to_s]
- # when String
- # groups = groups.split(/\s*,\s*/)
- # else
- # raise Puppet::DevError, "got invalid groups value #{groups.class} of type #{groups}"
- # end
- # # Get just the groups we need to modify
- # diff = groups - (@is || [])
- #
- # data = {}
- # open("| #{command(:nireport)} / /groups name users") do |file|
- # file.each do |line|
- # name, members = line.split(/\s+/)
- #
- # if members.nil? or members =~ /NoValue/
- # data[name] = []
- # else
- # # Add each diff group's current members
- # data[name] = members.split(/,/)
- # end
- # end
- # end
- #
- # user = @resource[:name]
- # data.each do |name, members|
- # if members.include? user and groups.include? name
- # # I'm in the group and should be
- # next
- # elsif members.include? user
- # # I'm in the group and shouldn't be
- # setuserlist(name, members - [user])
- # elsif groups.include? name
- # # I'm not in the group and should be
- # setuserlist(name, members + [user])
- # else
- # # I'm not in the group and shouldn't be
- # next
- # end
- # end
- end
+ # This is really lame. We have to iterate over each
+ # of the groups and add us to them.
+ def groups=(groups)
+ # case groups
+ # when Fixnum
+ # groups = [groups.to_s]
+ # when String
+ # groups = groups.split(/\s*,\s*/)
+ # else
+ # raise Puppet::DevError, "got invalid groups value #{groups.class} of type #{groups}"
+ # end
+ # # Get just the groups we need to modify
+ # diff = groups - (@is || [])
+ #
+ # data = {}
+ # open("| #{command(:nireport)} / /groups name users") do |file|
+ # file.each do |line|
+ # name, members = line.split(/\s+/)
+ #
+ # if members.nil? or members =~ /NoValue/
+ # data[name] = []
+ # else
+ # # Add each diff group's current members
+ # data[name] = members.split(/,/)
+ # end
+ # end
+ # end
+ #
+ # user = @resource[:name]
+ # data.each do |name, members|
+ # if members.include? user and groups.include? name
+ # # I'm in the group and should be
+ # next
+ # elsif members.include? user
+ # # I'm in the group and shouldn't be
+ # setuserlist(name, members - [user])
+ # elsif groups.include? name
+ # # I'm not in the group and should be
+ # setuserlist(name, members + [user])
+ # else
+ # # I'm not in the group and shouldn't be
+ # next
+ # end
+ # end
+ end
end
diff --git a/lib/puppet/provider/user/hpux.rb b/lib/puppet/provider/user/hpux.rb
index db8dd194e..50506c4cd 100644
--- a/lib/puppet/provider/user/hpux.rb
+++ b/lib/puppet/provider/user/hpux.rb
@@ -1,30 +1,30 @@
Puppet::Type.type(:user).provide :hpuxuseradd, :parent => :useradd do
- desc "User management for hp-ux! Undocumented switch to special usermod because HP-UX regular usermod is TOO STUPID to change stuff while the user is logged in."
+ desc "User management for hp-ux! Undocumented switch to special usermod because HP-UX regular usermod is TOO STUPID to change stuff while the user is logged in."
- defaultfor :operatingsystem => "hp-ux"
- confine :operatingsystem => "hp-ux"
+ defaultfor :operatingsystem => "hp-ux"
+ confine :operatingsystem => "hp-ux"
- commands :modify => "/usr/sam/lbin/usermod.sam", :delete => "/usr/sam/lbin/userdel.sam", :add => "/usr/sbin/useradd"
- options :comment, :method => :gecos
- options :groups, :flag => "-G"
- options :home, :flag => "-d", :method => :dir
+ commands :modify => "/usr/sam/lbin/usermod.sam", :delete => "/usr/sam/lbin/userdel.sam", :add => "/usr/sbin/useradd"
+ options :comment, :method => :gecos
+ options :groups, :flag => "-G"
+ options :home, :flag => "-d", :method => :dir
- verify :gid, "GID must be an integer" do |value|
- value.is_a? Integer
- end
+ verify :gid, "GID must be an integer" do |value|
+ value.is_a? Integer
+ end
- verify :groups, "Groups must be comma-separated" do |value|
- value !~ /\s/
- end
+ verify :groups, "Groups must be comma-separated" do |value|
+ value !~ /\s/
+ end
- has_features :manages_homedir, :allows_duplicates
+ has_features :manages_homedir, :allows_duplicates
- def deletecmd
- super.insert(1,"-F")
- end
+ def deletecmd
+ super.insert(1,"-F")
+ end
- def modifycmd(param,value)
- super.insert(1,"-F")
- end
+ def modifycmd(param,value)
+ super.insert(1,"-F")
+ end
end
diff --git a/lib/puppet/provider/user/ldap.rb b/lib/puppet/provider/user/ldap.rb
index 406ed0f93..df082c569 100644
--- a/lib/puppet/provider/user/ldap.rb
+++ b/lib/puppet/provider/user/ldap.rb
@@ -1,129 +1,129 @@
require 'puppet/provider/ldap'
Puppet::Type.type(:user).provide :ldap, :parent => Puppet::Provider::Ldap do
- desc "User management via ``ldap``. This provider requires that you
- have valid values for all of the ldap-related settings,
- including ``ldapbase``. You will also almost definitely need settings
- for ``ldapuser`` and ``ldappassword``, so that your clients can write
- to ldap.
-
- Note that this provider will automatically generate a UID for you if
- you do not specify one, but it is a potentially expensive operation,
- as it iterates across all existing users to pick the appropriate next
- one."
-
- confine :feature => :ldap, :false => (Puppet[:ldapuser] == "")
-
- has_feature :manages_passwords
-
- manages(:posixAccount, :person).at("ou=People").named_by(:uid).and.maps :name => :uid,
- :password => :userPassword,
- :comment => :cn,
- :uid => :uidNumber,
- :gid => :gidNumber,
- :home => :homeDirectory,
- :shell => :loginShell
-
- # Use the last field of a space-separated array as
- # the sn. LDAP requires a surname, for some stupid reason.
- manager.generates(:sn).from(:cn).with do |cn|
- x = 1
- cn[0].split(/\s+/)[-1]
+ desc "User management via ``ldap``. This provider requires that you
+ have valid values for all of the ldap-related settings,
+ including ``ldapbase``. You will also almost definitely need settings
+ for ``ldapuser`` and ``ldappassword``, so that your clients can write
+ to ldap.
+
+ Note that this provider will automatically generate a UID for you if
+ you do not specify one, but it is a potentially expensive operation,
+ as it iterates across all existing users to pick the appropriate next
+ one."
+
+ confine :feature => :ldap, :false => (Puppet[:ldapuser] == "")
+
+ has_feature :manages_passwords
+
+ manages(:posixAccount, :person).at("ou=People").named_by(:uid).and.maps :name => :uid,
+ :password => :userPassword,
+ :comment => :cn,
+ :uid => :uidNumber,
+ :gid => :gidNumber,
+ :home => :homeDirectory,
+ :shell => :loginShell
+
+ # Use the last field of a space-separated array as
+ # the sn. LDAP requires a surname, for some stupid reason.
+ manager.generates(:sn).from(:cn).with do |cn|
+ x = 1
+ cn[0].split(/\s+/)[-1]
+ end
+
+ # Find the next uid after the current largest uid.
+ provider = self
+ manager.generates(:uidNumber).with do
+ largest = 500
+ if existing = provider.manager.search
+ existing.each do |hash|
+ next unless value = hash[:uid]
+ num = value[0].to_i
+ largest = num if num > largest
+ end
end
-
- # Find the next uid after the current largest uid.
- provider = self
- manager.generates(:uidNumber).with do
- largest = 500
- if existing = provider.manager.search
- existing.each do |hash|
- next unless value = hash[:uid]
- num = value[0].to_i
- largest = num if num > largest
- end
- end
- largest + 1
+ largest + 1
+ end
+
+ # Convert our gid to a group name, if necessary.
+ def gid=(value)
+ value = group2id(value) unless [Fixnum, Bignum].include?(value.class)
+
+ @property_hash[:gid] = value
+ end
+
+ # Find all groups this user is a member of in ldap.
+ def groups
+ # We want to cache the current result, so we know if we
+ # have to remove old values.
+ unless @property_hash[:groups]
+ unless result = group_manager.search("memberUid=#{name}")
+ return @property_hash[:groups] = :absent
+ end
+
+ return @property_hash[:groups] = result.collect { |r| r[:name] }.sort.join(",")
end
+ @property_hash[:groups]
+ end
- # Convert our gid to a group name, if necessary.
- def gid=(value)
- value = group2id(value) unless [Fixnum, Bignum].include?(value.class)
+ # Manage the list of groups this user is a member of.
+ def groups=(values)
+ should = values.split(",")
- @property_hash[:gid] = value
+ if groups == :absent
+ is = []
+ else
+ is = groups.split(",")
end
- # Find all groups this user is a member of in ldap.
- def groups
- # We want to cache the current result, so we know if we
- # have to remove old values.
- unless @property_hash[:groups]
- unless result = group_manager.search("memberUid=#{name}")
- return @property_hash[:groups] = :absent
- end
-
- return @property_hash[:groups] = result.collect { |r| r[:name] }.sort.join(",")
- end
- @property_hash[:groups]
- end
+ modes = {}
+ [is, should].flatten.uniq.each do |group|
+ # Skip it when they're in both
+ next if is.include?(group) and should.include?(group)
- # Manage the list of groups this user is a member of.
- def groups=(values)
- should = values.split(",")
+ # We're adding a group.
+ modes[group] = :add and next unless is.include?(group)
- if groups == :absent
- is = []
- else
- is = groups.split(",")
- end
+ # We're removing a group.
+ modes[group] = :remove and next unless should.include?(group)
+ end
- modes = {}
- [is, should].flatten.uniq.each do |group|
- # Skip it when they're in both
- next if is.include?(group) and should.include?(group)
+ modes.each do |group, form|
+ self.fail "Could not find ldap group #{group}" unless ldap_group = group_manager.find(group)
- # We're adding a group.
- modes[group] = :add and next unless is.include?(group)
+ current = ldap_group[:members]
- # We're removing a group.
- modes[group] = :remove and next unless should.include?(group)
+ if form == :add
+ if current.is_a?(Array) and ! current.empty?
+ new = current + [name]
+ else
+ new = [name]
end
+ else
+ new = current - [name]
+ new = :absent if new.empty?
+ end
- modes.each do |group, form|
- self.fail "Could not find ldap group #{group}" unless ldap_group = group_manager.find(group)
-
- current = ldap_group[:members]
-
- if form == :add
- if current.is_a?(Array) and ! current.empty?
- new = current + [name]
- else
- new = [name]
- end
- else
- new = current - [name]
- new = :absent if new.empty?
- end
-
- group_manager.update(group, {:ensure => :present, :members => current}, {:ensure => :present, :members => new})
- end
+ group_manager.update(group, {:ensure => :present, :members => current}, {:ensure => :present, :members => new})
end
+ end
- # Convert a gropu name to an id.
- def group2id(group)
- Puppet::Type.type(:group).provider(:ldap).name2id(group)
- end
+ # Convert a gropu name to an id.
+ def group2id(group)
+ Puppet::Type.type(:group).provider(:ldap).name2id(group)
+ end
- private
+ private
- def group_manager
- Puppet::Type.type(:group).provider(:ldap).manager
- end
+ def group_manager
+ Puppet::Type.type(:group).provider(:ldap).manager
+ end
- def group_properties(values)
- if values.empty? or values == :absent
- {:ensure => :present}
- else
- {:ensure => :present, :members => values}
- end
+ def group_properties(values)
+ if values.empty? or values == :absent
+ {:ensure => :present}
+ else
+ {:ensure => :present, :members => values}
end
+ end
end
diff --git a/lib/puppet/provider/user/pw.rb b/lib/puppet/provider/user/pw.rb
index 7d3eda281..345d924bf 100644
--- a/lib/puppet/provider/user/pw.rb
+++ b/lib/puppet/provider/user/pw.rb
@@ -1,41 +1,41 @@
require 'puppet/provider/nameservice/pw'
Puppet::Type.type(:user).provide :pw, :parent => Puppet::Provider::NameService::PW do
- desc "User management via ``pw`` on FreeBSD."
-
- commands :pw => "pw"
- has_features :manages_homedir, :allows_duplicates
-
- defaultfor :operatingsystem => :freebsd
-
- options :home, :flag => "-d", :method => :dir
- options :comment, :method => :gecos
- options :groups, :flag => "-G"
-
- verify :gid, "GID must be an integer" do |value|
- value.is_a? Integer
+ desc "User management via ``pw`` on FreeBSD."
+
+ commands :pw => "pw"
+ has_features :manages_homedir, :allows_duplicates
+
+ defaultfor :operatingsystem => :freebsd
+
+ options :home, :flag => "-d", :method => :dir
+ options :comment, :method => :gecos
+ options :groups, :flag => "-G"
+
+ verify :gid, "GID must be an integer" do |value|
+ value.is_a? Integer
+ end
+
+ verify :groups, "Groups must be comma-separated" do |value|
+ value !~ /\s/
+ end
+
+ def addcmd
+ cmd = [command(:pw), "useradd", @resource[:name]]
+ @resource.class.validproperties.each do |property|
+ next if property == :ensure
+ # the value needs to be quoted, mostly because -c might
+ # have spaces in it
+ if value = @resource.should(property) and value != ""
+ cmd << flag(property) << value
+ end
end
- verify :groups, "Groups must be comma-separated" do |value|
- value !~ /\s/
- end
-
- def addcmd
- cmd = [command(:pw), "useradd", @resource[:name]]
- @resource.class.validproperties.each do |property|
- next if property == :ensure
- # the value needs to be quoted, mostly because -c might
- # have spaces in it
- if value = @resource.should(property) and value != ""
- cmd << flag(property) << value
- end
- end
+ cmd << "-o" if @resource.allowdupe?
- cmd << "-o" if @resource.allowdupe?
+ cmd << "-m" if @resource.managehome?
- cmd << "-m" if @resource.managehome?
-
- cmd
- end
+ cmd
+ end
end
diff --git a/lib/puppet/provider/user/user_role_add.rb b/lib/puppet/provider/user/user_role_add.rb
index 7c7c9e315..ea1b01b3b 100644
--- a/lib/puppet/provider/user/user_role_add.rb
+++ b/lib/puppet/provider/user/user_role_add.rb
@@ -2,177 +2,177 @@ require 'puppet/util/user_attr'
Puppet::Type.type(:user).provide :user_role_add, :parent => :useradd, :source => :useradd do
- desc "User management inherits ``useradd`` and adds logic to manage roles on Solaris using roleadd."
-
- defaultfor :operatingsystem => :solaris
-
- commands :add => "useradd", :delete => "userdel", :modify => "usermod", :role_add => "roleadd", :role_delete => "roledel", :role_modify => "rolemod"
- options :home, :flag => "-d", :method => :dir
- options :comment, :method => :gecos
- options :groups, :flag => "-G"
- options :roles, :flag => "-R"
- options :auths, :flag => "-A"
- options :profiles, :flag => "-P"
-
- verify :gid, "GID must be an integer" do |value|
- value.is_a? Integer
- end
-
- verify :groups, "Groups must be comma-separated" do |value|
- value !~ /\s/
- end
-
- has_features :manages_homedir, :allows_duplicates, :manages_solaris_rbac, :manages_passwords
-
- #must override this to hand the keyvalue pairs
- def add_properties
- cmd = []
- Puppet::Type.type(:user).validproperties.each do |property|
- #skip the password because we can't create it with the solaris useradd
- next if [:ensure, :password].include?(property)
- # 1680 Now you can set the hashed passwords on solaris:lib/puppet/provider/user/user_role_add.rb
- # the value needs to be quoted, mostly because -c might
- # have spaces in it
- if value = @resource.should(property) and value != ""
- if property == :keys
- cmd += build_keys_cmd(value)
- else
- cmd << flag(property) << value
- end
- end
- end
- cmd
- end
-
- def user_attributes
- @user_attributes ||= UserAttr.get_attributes_by_name(@resource[:name])
- end
-
- def flush
- @user_attributes = nil
- end
-
- def command(cmd)
- cmd = ("role_#{cmd}").intern if is_role? or (!exists? and @resource[:ensure] == :role)
- super(cmd)
- end
-
- def is_role?
- user_attributes and user_attributes[:type] == "role"
- end
-
- def run(cmd, msg)
- execute(cmd)
- rescue Puppet::ExecutionFailure => detail
- raise Puppet::Error, "Could not #{msg} #{@resource.class.name} #{@resource.name}: #{detail}"
- end
-
- def transition(type)
- cmd = [command(:modify)]
- cmd << "-K" << "type=#{type}"
- cmd += add_properties
- cmd << @resource[:name]
- end
-
- def create
- if is_role?
- run(transition("normal"), "transition role to")
+ desc "User management inherits ``useradd`` and adds logic to manage roles on Solaris using roleadd."
+
+ defaultfor :operatingsystem => :solaris
+
+ commands :add => "useradd", :delete => "userdel", :modify => "usermod", :role_add => "roleadd", :role_delete => "roledel", :role_modify => "rolemod"
+ options :home, :flag => "-d", :method => :dir
+ options :comment, :method => :gecos
+ options :groups, :flag => "-G"
+ options :roles, :flag => "-R"
+ options :auths, :flag => "-A"
+ options :profiles, :flag => "-P"
+
+ verify :gid, "GID must be an integer" do |value|
+ value.is_a? Integer
+ end
+
+ verify :groups, "Groups must be comma-separated" do |value|
+ value !~ /\s/
+ end
+
+ has_features :manages_homedir, :allows_duplicates, :manages_solaris_rbac, :manages_passwords
+
+ #must override this to hand the keyvalue pairs
+ def add_properties
+ cmd = []
+ Puppet::Type.type(:user).validproperties.each do |property|
+ #skip the password because we can't create it with the solaris useradd
+ next if [:ensure, :password].include?(property)
+ # 1680 Now you can set the hashed passwords on solaris:lib/puppet/provider/user/user_role_add.rb
+ # the value needs to be quoted, mostly because -c might
+ # have spaces in it
+ if value = @resource.should(property) and value != ""
+ if property == :keys
+ cmd += build_keys_cmd(value)
else
- run(addcmd, "create")
+ cmd << flag(property) << value
end
- # added to handle case when password is specified
- self.password = @resource[:password] if @resource[:password]
- end
-
- def destroy
- run(deletecmd, "delete "+ (is_role? ? "role" : "user"))
- end
-
- def create_role
- if exists? and !is_role?
- run(transition("role"), "transition user to")
- else
- run(addcmd, "create role")
- end
- end
-
- def roles
- user_attributes[:roles] if user_attributes
- end
-
- def auths
- user_attributes[:auths] if user_attributes
- end
-
- def profiles
- user_attributes[:profiles] if user_attributes
- end
-
- def project
- user_attributes[:project] if user_attributes
- end
-
- def managed_attributes
- [:name, :type, :roles, :auths, :profiles, :project]
- end
-
- def remove_managed_attributes
- managed = managed_attributes
- user_attributes.select { |k,v| !managed.include?(k) }.inject({}) { |hash, array| hash[array[0]] = array[1]; hash }
- end
-
- def keys
- if user_attributes
- #we have to get rid of all the keys we are managing another way
- remove_managed_attributes
- end
- end
-
- def build_keys_cmd(keys_hash)
- cmd = []
- keys_hash.each do |k,v|
- cmd << "-K" << "#{k}=#{v}"
- end
- cmd
- end
-
- def keys=(keys_hash)
- run([command(:modify)] + build_keys_cmd(keys_hash) << @resource[:name], "modify attribute key pairs")
- end
-
- #Read in /etc/shadow, find the line for this user (skipping comments, because who knows) and return the hashed pw (the second entry)
- #No abstraction, all esoteric knowledge of file formats, yay
- def password
- #got perl?
- if ary = File.readlines("/etc/shadow").reject { |r| r =~ /^[^\w]/}.collect { |l| l.split(':')[0..1] }.find { |user, passwd| user == @resource[:name] }
- pass = ary[1]
- end
- pass
- end
-
- #Read in /etc/shadow, find the line for our used and rewrite it with the new pw
- #Smooth like 80 grit
- def password=(cryptopw)
- begin
- File.open("/etc/shadow", "r") do |shadow|
- File.open("/etc/shadow_tmp", "w", 0600) do |shadow_tmp|
- while line = shadow.gets
- line_arr = line.split(':')
- if line_arr[0] == @resource[:name]
- line_arr[1] = cryptopw
- line = line_arr.join(':')
- end
- shadow_tmp.print line
- end
- end
+ end
+ end
+ cmd
+ end
+
+ def user_attributes
+ @user_attributes ||= UserAttr.get_attributes_by_name(@resource[:name])
+ end
+
+ def flush
+ @user_attributes = nil
+ end
+
+ def command(cmd)
+ cmd = ("role_#{cmd}").intern if is_role? or (!exists? and @resource[:ensure] == :role)
+ super(cmd)
+ end
+
+ def is_role?
+ user_attributes and user_attributes[:type] == "role"
+ end
+
+ def run(cmd, msg)
+ execute(cmd)
+ rescue Puppet::ExecutionFailure => detail
+ raise Puppet::Error, "Could not #{msg} #{@resource.class.name} #{@resource.name}: #{detail}"
+ end
+
+ def transition(type)
+ cmd = [command(:modify)]
+ cmd << "-K" << "type=#{type}"
+ cmd += add_properties
+ cmd << @resource[:name]
+ end
+
+ def create
+ if is_role?
+ run(transition("normal"), "transition role to")
+ else
+ run(addcmd, "create")
+ end
+ # added to handle case when password is specified
+ self.password = @resource[:password] if @resource[:password]
+ end
+
+ def destroy
+ run(deletecmd, "delete "+ (is_role? ? "role" : "user"))
+ end
+
+ def create_role
+ if exists? and !is_role?
+ run(transition("role"), "transition user to")
+ else
+ run(addcmd, "create role")
+ end
+ end
+
+ def roles
+ user_attributes[:roles] if user_attributes
+ end
+
+ def auths
+ user_attributes[:auths] if user_attributes
+ end
+
+ def profiles
+ user_attributes[:profiles] if user_attributes
+ end
+
+ def project
+ user_attributes[:project] if user_attributes
+ end
+
+ def managed_attributes
+ [:name, :type, :roles, :auths, :profiles, :project]
+ end
+
+ def remove_managed_attributes
+ managed = managed_attributes
+ user_attributes.select { |k,v| !managed.include?(k) }.inject({}) { |hash, array| hash[array[0]] = array[1]; hash }
+ end
+
+ def keys
+ if user_attributes
+ #we have to get rid of all the keys we are managing another way
+ remove_managed_attributes
+ end
+ end
+
+ def build_keys_cmd(keys_hash)
+ cmd = []
+ keys_hash.each do |k,v|
+ cmd << "-K" << "#{k}=#{v}"
+ end
+ cmd
+ end
+
+ def keys=(keys_hash)
+ run([command(:modify)] + build_keys_cmd(keys_hash) << @resource[:name], "modify attribute key pairs")
+ end
+
+ #Read in /etc/shadow, find the line for this user (skipping comments, because who knows) and return the hashed pw (the second entry)
+ #No abstraction, all esoteric knowledge of file formats, yay
+ def password
+ #got perl?
+ if ary = File.readlines("/etc/shadow").reject { |r| r =~ /^[^\w]/}.collect { |l| l.split(':')[0..1] }.find { |user, passwd| user == @resource[:name] }
+ pass = ary[1]
+ end
+ pass
+ end
+
+ #Read in /etc/shadow, find the line for our used and rewrite it with the new pw
+ #Smooth like 80 grit
+ def password=(cryptopw)
+ begin
+ File.open("/etc/shadow", "r") do |shadow|
+ File.open("/etc/shadow_tmp", "w", 0600) do |shadow_tmp|
+ while line = shadow.gets
+ line_arr = line.split(':')
+ if line_arr[0] == @resource[:name]
+ line_arr[1] = cryptopw
+ line = line_arr.join(':')
end
- File.rename("/etc/shadow_tmp", "/etc/shadow")
- rescue => detail
- fail "Could not write temporary shadow file: #{detail}"
- ensure
- # Make sure this *always* gets deleted
- File.unlink("/etc/shadow_tmp") if File.exist?("/etc/shadow_tmp")
+ shadow_tmp.print line
+ end
end
- end
+ end
+ File.rename("/etc/shadow_tmp", "/etc/shadow")
+ rescue => detail
+ fail "Could not write temporary shadow file: #{detail}"
+ ensure
+ # Make sure this *always* gets deleted
+ File.unlink("/etc/shadow_tmp") if File.exist?("/etc/shadow_tmp")
+ end
+ end
end
diff --git a/lib/puppet/provider/user/useradd.rb b/lib/puppet/provider/user/useradd.rb
index 7645969ff..ec87694d7 100644
--- a/lib/puppet/provider/user/useradd.rb
+++ b/lib/puppet/provider/user/useradd.rb
@@ -1,69 +1,69 @@
require 'puppet/provider/nameservice/objectadd'
Puppet::Type.type(:user).provide :useradd, :parent => Puppet::Provider::NameService::ObjectAdd do
- desc "User management via ``useradd`` and its ilk. Note that you will need to install the ``Shadow Password`` Ruby library often known as ruby-libshadow to manage user passwords."
+ desc "User management via ``useradd`` and its ilk. Note that you will need to install the ``Shadow Password`` Ruby library often known as ruby-libshadow to manage user passwords."
- commands :add => "useradd", :delete => "userdel", :modify => "usermod"
+ commands :add => "useradd", :delete => "userdel", :modify => "usermod"
- options :home, :flag => "-d", :method => :dir
- options :comment, :method => :gecos
- options :groups, :flag => "-G"
+ options :home, :flag => "-d", :method => :dir
+ options :comment, :method => :gecos
+ options :groups, :flag => "-G"
- verify :gid, "GID must be an integer" do |value|
- value.is_a? Integer
- end
+ verify :gid, "GID must be an integer" do |value|
+ value.is_a? Integer
+ end
- verify :groups, "Groups must be comma-separated" do |value|
- value !~ /\s/
- end
+ verify :groups, "Groups must be comma-separated" do |value|
+ value !~ /\s/
+ end
- has_features :manages_homedir, :allows_duplicates
+ has_features :manages_homedir, :allows_duplicates
- has_feature :manages_passwords if Puppet.features.libshadow?
+ has_feature :manages_passwords if Puppet.features.libshadow?
- def check_allow_dup
- @resource.allowdupe? ? ["-o"] : []
- end
+ def check_allow_dup
+ @resource.allowdupe? ? ["-o"] : []
+ end
- def check_manage_home
- cmd = []
- if @resource.managehome?
- cmd << "-m"
- elsif %w{Fedora RedHat CentOS OEL OVS}.include?(Facter.value("operatingsystem"))
- cmd << "-M"
- end
- cmd
+ def check_manage_home
+ cmd = []
+ if @resource.managehome?
+ cmd << "-m"
+ elsif %w{Fedora RedHat CentOS OEL OVS}.include?(Facter.value("operatingsystem"))
+ cmd << "-M"
end
+ cmd
+ end
- def add_properties
- cmd = []
- Puppet::Type.type(:user).validproperties.each do |property|
- next if property == :ensure
- # the value needs to be quoted, mostly because -c might
- # have spaces in it
- if value = @resource.should(property) and value != ""
- cmd << flag(property) << value
- end
- end
- cmd
+ def add_properties
+ cmd = []
+ Puppet::Type.type(:user).validproperties.each do |property|
+ next if property == :ensure
+ # the value needs to be quoted, mostly because -c might
+ # have spaces in it
+ if value = @resource.should(property) and value != ""
+ cmd << flag(property) << value
+ end
end
+ cmd
+ end
- def addcmd
- cmd = [command(:add)]
- cmd += add_properties
- cmd += check_allow_dup
- cmd += check_manage_home
- cmd << @resource[:name]
- end
+ def addcmd
+ cmd = [command(:add)]
+ cmd += add_properties
+ cmd += check_allow_dup
+ cmd += check_manage_home
+ cmd << @resource[:name]
+ end
- # Retrieve the password using the Shadow Password library
- def password
- if Puppet.features.libshadow?
- if ent = Shadow::Passwd.getspnam(@resource.name)
- return ent.sp_pwdp
- end
- end
- :absent
+ # Retrieve the password using the Shadow Password library
+ def password
+ if Puppet.features.libshadow?
+ if ent = Shadow::Passwd.getspnam(@resource.name)
+ return ent.sp_pwdp
+ end
end
+ :absent
+ end
end
diff --git a/lib/puppet/provider/zfs/solaris.rb b/lib/puppet/provider/zfs/solaris.rb
index 418c902bd..85d054f86 100644
--- a/lib/puppet/provider/zfs/solaris.rb
+++ b/lib/puppet/provider/zfs/solaris.rb
@@ -1,45 +1,45 @@
Puppet::Type.type(:zfs).provide(:solaris) do
- desc "Provider for Solaris zfs."
-
- commands :zfs => "/usr/sbin/zfs"
- defaultfor :operatingsystem => :solaris
-
- def add_properties
- properties = []
- Puppet::Type.type(:zfs).validproperties.each do |property|
- next if property == :ensure
- if value = @resource[property] and value != ""
- properties << "-o" << "#{property}=#{value}"
- end
- end
- properties
+ desc "Provider for Solaris zfs."
+
+ commands :zfs => "/usr/sbin/zfs"
+ defaultfor :operatingsystem => :solaris
+
+ def add_properties
+ properties = []
+ Puppet::Type.type(:zfs).validproperties.each do |property|
+ next if property == :ensure
+ if value = @resource[property] and value != ""
+ properties << "-o" << "#{property}=#{value}"
+ end
end
-
- def create
- zfs *([:create] + add_properties + [@resource[:name]])
- end
-
- def destroy
- zfs(:destroy, @resource[:name])
+ properties
+ end
+
+ def create
+ zfs *([:create] + add_properties + [@resource[:name]])
+ end
+
+ def destroy
+ zfs(:destroy, @resource[:name])
+ end
+
+ def exists?
+ if zfs(:list).split("\n").detect { |line| line.split("\s")[0] == @resource[:name] }
+ true
+ else
+ false
end
+ end
- def exists?
- if zfs(:list).split("\n").detect { |line| line.split("\s")[0] == @resource[:name] }
- true
- else
- false
- end
+ [:mountpoint, :compression, :copies, :quota, :reservation, :sharenfs, :snapdir].each do |field|
+ define_method(field) do
+ zfs(:get, "-H", "-o", "value", field, @resource[:name]).strip
end
- [:mountpoint, :compression, :copies, :quota, :reservation, :sharenfs, :snapdir].each do |field|
- define_method(field) do
- zfs(:get, "-H", "-o", "value", field, @resource[:name]).strip
- end
-
- define_method(field.to_s + "=") do |should|
- zfs(:set, "#{field}=#{should}", @resource[:name])
- end
+ define_method(field.to_s + "=") do |should|
+ zfs(:set, "#{field}=#{should}", @resource[:name])
end
+ end
end
diff --git a/lib/puppet/provider/zone/solaris.rb b/lib/puppet/provider/zone/solaris.rb
index 33b1bc122..c11444993 100644
--- a/lib/puppet/provider/zone/solaris.rb
+++ b/lib/puppet/provider/zone/solaris.rb
@@ -1,257 +1,257 @@
Puppet::Type.type(:zone).provide(:solaris) do
- desc "Provider for Solaris Zones."
+ desc "Provider for Solaris Zones."
- commands :adm => "/usr/sbin/zoneadm", :cfg => "/usr/sbin/zonecfg"
- defaultfor :operatingsystem => :solaris
+ commands :adm => "/usr/sbin/zoneadm", :cfg => "/usr/sbin/zonecfg"
+ defaultfor :operatingsystem => :solaris
- mk_resource_methods
+ mk_resource_methods
- # Convert the output of a list into a hash
- def self.line2hash(line)
- fields = [:id, :name, :ensure, :path]
+ # Convert the output of a list into a hash
+ def self.line2hash(line)
+ fields = [:id, :name, :ensure, :path]
- properties = {}
- line.split(":").each_with_index { |value, index|
- next unless fields[index]
- properties[fields[index]] = value
- }
+ properties = {}
+ line.split(":").each_with_index { |value, index|
+ next unless fields[index]
+ properties[fields[index]] = value
+ }
- # Configured but not installed zones do not have IDs
- properties.delete(:id) if properties[:id] == "-"
+ # Configured but not installed zones do not have IDs
+ properties.delete(:id) if properties[:id] == "-"
- properties[:ensure] = symbolize(properties[:ensure])
+ properties[:ensure] = symbolize(properties[:ensure])
- properties
- end
+ properties
+ end
- def self.instances
- # LAK:NOTE See http://snurl.com/21zf8 [groups_google_com]
- x = adm(:list, "-cp").split("\n").collect do |line|
- new(line2hash(line))
- end
+ def self.instances
+ # LAK:NOTE See http://snurl.com/21zf8 [groups_google_com]
+ x = adm(:list, "-cp").split("\n").collect do |line|
+ new(line2hash(line))
end
-
- # Perform all of our configuration steps.
- def configure
- # If the thing is entirely absent, then we need to create the config.
- # Is there someway to get this on one line?
- str = "create -b #{@resource[:create_args]}\nset zonepath=#{@resource[:path]}\n"
-
- # Then perform all of our configuration steps. It's annoying
- # that we need this much internal info on the resource.
- @resource.send(:properties).each do |property|
- str += property.configtext + "\n" if property.is_a? ZoneConfigProperty and ! property.insync?(properties[property.name])
- end
-
- str += "commit\n"
- setconfig(str)
+ end
+
+ # Perform all of our configuration steps.
+ def configure
+ # If the thing is entirely absent, then we need to create the config.
+ # Is there someway to get this on one line?
+ str = "create -b #{@resource[:create_args]}\nset zonepath=#{@resource[:path]}\n"
+
+ # Then perform all of our configuration steps. It's annoying
+ # that we need this much internal info on the resource.
+ @resource.send(:properties).each do |property|
+ str += property.configtext + "\n" if property.is_a? ZoneConfigProperty and ! property.insync?(properties[property.name])
end
- def destroy
- zonecfg :delete, "-F"
+ str += "commit\n"
+ setconfig(str)
+ end
+
+ def destroy
+ zonecfg :delete, "-F"
+ end
+
+ def exists?
+ properties[:ensure] != :absent
+ end
+
+ # Clear out the cached values.
+ def flush
+ @property_hash.clear
+ end
+
+ def install(dummy_argument=:work_arround_for_ruby_GC_bug)
+ if @resource[:clone] # TODO: add support for "-s snapshot"
+ zoneadm :clone, @resource[:clone]
+ elsif @resource[:install_args]
+ zoneadm :install, @resource[:install_args].split(" ")
+ else
+ zoneadm :install
end
+ end
+
+ # Look up the current status.
+ def properties
+ if @property_hash.empty?
+ @property_hash = status || {}
+ if @property_hash.empty?
+ @property_hash[:ensure] = :absent
+ else
+ @resource.class.validproperties.each do |name|
+ @property_hash[name] ||= :absent
+ end
+ end
- def exists?
- properties[:ensure] != :absent
end
-
- # Clear out the cached values.
- def flush
- @property_hash.clear
+ @property_hash.dup
+ end
+
+ # We need a way to test whether a zone is in process. Our 'ensure'
+ # property models the static states, but we need to handle the temporary ones.
+ def processing?
+ if hash = status
+ case hash[:ensure]
+ when "incomplete", "ready", "shutting_down"
+ true
+ else
+ false
+ end
+ else
+ false
end
-
- def install(dummy_argument=:work_arround_for_ruby_GC_bug)
- if @resource[:clone] # TODO: add support for "-s snapshot"
- zoneadm :clone, @resource[:clone]
- elsif @resource[:install_args]
- zoneadm :install, @resource[:install_args].split(" ")
+ end
+
+ # Collect the configuration of the zone.
+ def getconfig
+ output = zonecfg :info
+
+ name = nil
+ current = nil
+ hash = {}
+ output.split("\n").each do |line|
+ case line
+ when /^(\S+):\s*$/
+ name = $1
+ current = nil # reset it
+ when /^(\S+):\s*(.+)$/
+ hash[$1.intern] = $2
+ when /^\s+(\S+):\s*(.+)$/
+ if name
+ hash[name] = [] unless hash.include? name
+
+ unless current
+ current = {}
+ hash[name] << current
+ end
+ current[$1.intern] = $2
else
- zoneadm :install
+ err "Ignoring '#{line}'"
end
+ else
+ debug "Ignoring zone output '#{line}'"
+ end
end
- # Look up the current status.
- def properties
- if @property_hash.empty?
- @property_hash = status || {}
- if @property_hash.empty?
- @property_hash[:ensure] = :absent
- else
- @resource.class.validproperties.each do |name|
- @property_hash[name] ||= :absent
- end
- end
+ hash
+ end
- end
- @property_hash.dup
+ # Execute a configuration string. Can't be private because it's called
+ # by the properties.
+ def setconfig(str)
+ command = "#{command(:cfg)} -z #{@resource[:name]} -f -"
+ debug "Executing '#{command}' in zone #{@resource[:name]} with '#{str}'"
+ IO.popen(command, "w") do |pipe|
+ pipe.puts str
end
- # We need a way to test whether a zone is in process. Our 'ensure'
- # property models the static states, but we need to handle the temporary ones.
- def processing?
- if hash = status
- case hash[:ensure]
- when "incomplete", "ready", "shutting_down"
- true
- else
- false
- end
- else
- false
- end
+ unless $CHILD_STATUS == 0
+ raise ArgumentError, "Failed to apply configuration"
end
+ end
- # Collect the configuration of the zone.
- def getconfig
- output = zonecfg :info
-
- name = nil
- current = nil
- hash = {}
- output.split("\n").each do |line|
- case line
- when /^(\S+):\s*$/
- name = $1
- current = nil # reset it
- when /^(\S+):\s*(.+)$/
- hash[$1.intern] = $2
- when /^\s+(\S+):\s*(.+)$/
- if name
- hash[name] = [] unless hash.include? name
-
- unless current
- current = {}
- hash[name] << current
- end
- current[$1.intern] = $2
- else
- err "Ignoring '#{line}'"
- end
- else
- debug "Ignoring zone output '#{line}'"
- end
- end
+ def start
+ # Check the sysidcfg stuff
+ if cfg = @resource[:sysidcfg]
+ zoneetc = File.join(@resource[:path], "root", "etc")
+ sysidcfg = File.join(zoneetc, "sysidcfg")
- hash
- end
+ # if the zone root isn't present "ready" the zone
+ # which makes zoneadmd mount the zone root
+ zoneadm :ready unless File.directory?(zoneetc)
- # Execute a configuration string. Can't be private because it's called
- # by the properties.
- def setconfig(str)
- command = "#{command(:cfg)} -z #{@resource[:name]} -f -"
- debug "Executing '#{command}' in zone #{@resource[:name]} with '#{str}'"
- IO.popen(command, "w") do |pipe|
- pipe.puts str
- end
-
- unless $CHILD_STATUS == 0
- raise ArgumentError, "Failed to apply configuration"
+ unless File.exists?(sysidcfg)
+ begin
+ File.open(sysidcfg, "w", 0600) do |f|
+ f.puts cfg
+ end
+ rescue => detail
+ puts detail.stacktrace if Puppet[:debug]
+ raise Puppet::Error, "Could not create sysidcfg: #{detail}"
end
+ end
end
- def start
- # Check the sysidcfg stuff
- if cfg = @resource[:sysidcfg]
- zoneetc = File.join(@resource[:path], "root", "etc")
- sysidcfg = File.join(zoneetc, "sysidcfg")
-
- # if the zone root isn't present "ready" the zone
- # which makes zoneadmd mount the zone root
- zoneadm :ready unless File.directory?(zoneetc)
-
- unless File.exists?(sysidcfg)
- begin
- File.open(sysidcfg, "w", 0600) do |f|
- f.puts cfg
- end
- rescue => detail
- puts detail.stacktrace if Puppet[:debug]
- raise Puppet::Error, "Could not create sysidcfg: #{detail}"
- end
- end
- end
+ zoneadm :boot
+ end
- zoneadm :boot
+ # Return a hash of the current status of this zone.
+ def status
+ begin
+ output = adm "-z", @resource[:name], :list, "-p"
+ rescue Puppet::ExecutionFailure
+ return nil
end
- # Return a hash of the current status of this zone.
- def status
- begin
- output = adm "-z", @resource[:name], :list, "-p"
- rescue Puppet::ExecutionFailure
- return nil
- end
-
- main = self.class.line2hash(output.chomp)
+ main = self.class.line2hash(output.chomp)
- # Now add in the configuration information
- config_status.each do |name, value|
- main[name] = value
- end
-
- main
+ # Now add in the configuration information
+ config_status.each do |name, value|
+ main[name] = value
end
- def ready
- zoneadm :ready
- end
+ main
+ end
- def stop
- zoneadm :halt
- end
+ def ready
+ zoneadm :ready
+ end
- def unconfigure
- zonecfg :delete, "-F"
- end
+ def stop
+ zoneadm :halt
+ end
- def uninstall
- zoneadm :uninstall, "-F"
- end
+ def unconfigure
+ zonecfg :delete, "-F"
+ end
- private
+ def uninstall
+ zoneadm :uninstall, "-F"
+ end
- # Turn the results of getconfig into status information.
- def config_status
- config = getconfig
- result = {}
+ private
- result[:autoboot] = config[:autoboot] ? config[:autoboot].intern : :absent
- result[:pool] = config[:pool]
- result[:shares] = config[:shares]
- if dir = config["inherit-pkg-dir"]
- result[:inherit] = dir.collect { |dirs| dirs[:dir] }
- end
- result[:iptype] = config[:"ip-type"]
- if net = config["net"]
- result[:ip] = net.collect do |params|
- if params[:defrouter]
- "#{params[:physical]}:#{params[:address]}:#{params[:defrouter]}"
- elsif params[:address]
- "#{params[:physical]}:#{params[:address]}"
- else
- params[:physical]
- end
- end
- end
+ # Turn the results of getconfig into status information.
+ def config_status
+ config = getconfig
+ result = {}
- result
+ result[:autoboot] = config[:autoboot] ? config[:autoboot].intern : :absent
+ result[:pool] = config[:pool]
+ result[:shares] = config[:shares]
+ if dir = config["inherit-pkg-dir"]
+ result[:inherit] = dir.collect { |dirs| dirs[:dir] }
end
-
- def zoneadm(*cmd)
- adm("-z", @resource[:name], *cmd)
- rescue Puppet::ExecutionFailure => detail
- self.fail "Could not #{cmd[0]} zone: #{detail}"
+ result[:iptype] = config[:"ip-type"]
+ if net = config["net"]
+ result[:ip] = net.collect do |params|
+ if params[:defrouter]
+ "#{params[:physical]}:#{params[:address]}:#{params[:defrouter]}"
+ elsif params[:address]
+ "#{params[:physical]}:#{params[:address]}"
+ else
+ params[:physical]
+ end
+ end
end
- def zonecfg(*cmd)
- # You apparently can't get the configuration of the global zone
- return "" if self.name == "global"
+ result
+ end
- begin
- cfg("-z", self.name, *cmd)
- rescue Puppet::ExecutionFailure => detail
- self.fail "Could not #{cmd[0]} zone: #{detail}"
- end
+ def zoneadm(*cmd)
+ adm("-z", @resource[:name], *cmd)
+ rescue Puppet::ExecutionFailure => detail
+ self.fail "Could not #{cmd[0]} zone: #{detail}"
+ end
+
+ def zonecfg(*cmd)
+ # You apparently can't get the configuration of the global zone
+ return "" if self.name == "global"
+
+ begin
+ cfg("-z", self.name, *cmd)
+ rescue Puppet::ExecutionFailure => detail
+ self.fail "Could not #{cmd[0]} zone: #{detail}"
end
+ end
end
diff --git a/lib/puppet/provider/zpool/solaris.rb b/lib/puppet/provider/zpool/solaris.rb
index bfd37085a..e597c2ae1 100644
--- a/lib/puppet/provider/zpool/solaris.rb
+++ b/lib/puppet/provider/zpool/solaris.rb
@@ -1,114 +1,114 @@
Puppet::Type.type(:zpool).provide(:solaris) do
- desc "Provider for Solaris zpool."
-
- commands :zpool => "/usr/sbin/zpool"
- defaultfor :operatingsystem => :solaris
-
- def process_zpool_data(pool_array)
- if pool_array == []
- return Hash.new(:absent)
- end
- #get the name and get rid of it
- pool = Hash.new
- pool[:pool] = pool_array[0]
- pool_array.shift
-
- tmp = []
-
- #order matters here :(
- pool_array.reverse.each do |value|
- sym = nil
- case value
- when "spares"; sym = :spare
- when "logs"; sym = :log
- when "mirror", "raidz1", "raidz2"
- sym = value == "mirror" ? :mirror : :raidz
- pool[:raid_parity] = "raidz2" if value == "raidz2"
- else
- tmp << value
- sym = :disk if value == pool_array.first
- end
-
- if sym
- pool[sym] = pool[sym] ? pool[sym].unshift(tmp.reverse.join(' ')) : [tmp.reverse.join(' ')]
- tmp.clear
- end
- end
-
- pool
- end
+ desc "Provider for Solaris zpool."
- def get_pool_data
- #this is all voodoo dependent on the output from zpool
- zpool_data = %x{ zpool status #{@resource[:pool]}}.split("\n").select { |line| line.index("\t") == 0 }.collect { |l| l.strip.split("\s")[0] }
- zpool_data.shift
- zpool_data
- end
+ commands :zpool => "/usr/sbin/zpool"
+ defaultfor :operatingsystem => :solaris
- def current_pool
- @current_pool = process_zpool_data(get_pool_data) unless (defined?(@current_pool) and @current_pool)
- @current_pool
+ def process_zpool_data(pool_array)
+ if pool_array == []
+ return Hash.new(:absent)
end
-
- def flush
- @current_pool= nil
+ #get the name and get rid of it
+ pool = Hash.new
+ pool[:pool] = pool_array[0]
+ pool_array.shift
+
+ tmp = []
+
+ #order matters here :(
+ pool_array.reverse.each do |value|
+ sym = nil
+ case value
+ when "spares"; sym = :spare
+ when "logs"; sym = :log
+ when "mirror", "raidz1", "raidz2"
+ sym = value == "mirror" ? :mirror : :raidz
+ pool[:raid_parity] = "raidz2" if value == "raidz2"
+ else
+ tmp << value
+ sym = :disk if value == pool_array.first
+ end
+
+ if sym
+ pool[sym] = pool[sym] ? pool[sym].unshift(tmp.reverse.join(' ')) : [tmp.reverse.join(' ')]
+ tmp.clear
+ end
end
- #Adds log and spare
- def build_named(name)
- if prop = @resource[name.intern]
- [name] + prop.collect { |p| p.split(' ') }.flatten
- else
- []
- end
+ pool
+ end
+
+ def get_pool_data
+ #this is all voodoo dependent on the output from zpool
+ zpool_data = %x{ zpool status #{@resource[:pool]}}.split("\n").select { |line| line.index("\t") == 0 }.collect { |l| l.strip.split("\s")[0] }
+ zpool_data.shift
+ zpool_data
+ end
+
+ def current_pool
+ @current_pool = process_zpool_data(get_pool_data) unless (defined?(@current_pool) and @current_pool)
+ @current_pool
+ end
+
+ def flush
+ @current_pool= nil
+ end
+
+ #Adds log and spare
+ def build_named(name)
+ if prop = @resource[name.intern]
+ [name] + prop.collect { |p| p.split(' ') }.flatten
+ else
+ []
end
-
- #query for parity and set the right string
- def raidzarity
- @resource[:raid_parity] ? @resource[:raid_parity] : "raidz1"
+ end
+
+ #query for parity and set the right string
+ def raidzarity
+ @resource[:raid_parity] ? @resource[:raid_parity] : "raidz1"
+ end
+
+ #handle mirror or raid
+ def handle_multi_arrays(prefix, array)
+ array.collect{ |a| [prefix] + a.split(' ') }.flatten
+ end
+
+ #builds up the vdevs for create command
+ def build_vdevs
+ if disk = @resource[:disk]
+ disk.collect { |d| d.split(' ') }.flatten
+ elsif mirror = @resource[:mirror]
+ handle_multi_arrays("mirror", mirror)
+ elsif raidz = @resource[:raidz]
+ handle_multi_arrays(raidzarity, raidz)
end
+ end
- #handle mirror or raid
- def handle_multi_arrays(prefix, array)
- array.collect{ |a| [prefix] + a.split(' ') }.flatten
- end
+ def create
+ zpool(*([:create, @resource[:pool]] + build_vdevs + build_named("spare") + build_named("log")))
+ end
- #builds up the vdevs for create command
- def build_vdevs
- if disk = @resource[:disk]
- disk.collect { |d| d.split(' ') }.flatten
- elsif mirror = @resource[:mirror]
- handle_multi_arrays("mirror", mirror)
- elsif raidz = @resource[:raidz]
- handle_multi_arrays(raidzarity, raidz)
- end
- end
-
- def create
- zpool(*([:create, @resource[:pool]] + build_vdevs + build_named("spare") + build_named("log")))
- end
+ def delete
+ zpool :destroy, @resource[:pool]
+ end
- def delete
- zpool :destroy, @resource[:pool]
+ def exists?
+ if current_pool[:pool] == :absent
+ false
+ else
+ true
end
+ end
- def exists?
- if current_pool[:pool] == :absent
- false
- else
- true
- end
+ [:disk, :mirror, :raidz, :log, :spare].each do |field|
+ define_method(field) do
+ current_pool[field]
end
- [:disk, :mirror, :raidz, :log, :spare].each do |field|
- define_method(field) do
- current_pool[field]
- end
-
- define_method(field.to_s + "=") do |should|
- Puppet.warning "NO CHANGES BEING MADE: zpool #{field} does not match, should be '#{should}' currently is '#{current_pool[field]}'"
- end
+ define_method(field.to_s + "=") do |should|
+ Puppet.warning "NO CHANGES BEING MADE: zpool #{field} does not match, should be '#{should}' currently is '#{current_pool[field]}'"
end
+ end
end