newer pg module
[mirror/dsa-puppet.git] / 3rdparty / modules / postgresql / lib / puppet / provider / postgresql_replication_slot / ruby.rb
1 Puppet::Type.type(:postgresql_replication_slot).provide(:ruby) do
2   # For confinement
3   commands :psql => 'psql'
4
5   def self.instances
6     run_sql_command('SELECT * FROM pg_replication_slots;')[0].split("\n").select { |l| l =~ /\|/ }.map do |l|
7       name, *others = l.strip.split(/\s+\|\s+/)
8       new({
9         :name   => name,
10         :ensure => :present,
11       })
12     end
13   end
14
15   def self.prefetch(resources)
16     instances.each do |i|
17       if slot = resources[i.name]
18         slot.provider = i
19       end
20     end
21   end
22
23   def exists?
24     @property_hash[:ensure] == :present
25   end
26
27   def create
28     output = self.class.run_sql_command("SELECT * FROM pg_create_physical_replication_slot('#{resource[:name]}');")
29     if output[1].success?
30       @property_hash[:ensure] = :present
31     else
32       raise Puppet::Error, "Failed to create replication slot #{resource[:name]}:\n#{output[0]}"
33     end
34   end
35
36   def destroy
37     output = self.class.run_sql_command("SELECT pg_drop_replication_slot('#{resource[:name]}');")
38     if output[1].success?
39       @property_hash[:ensure] = :absent
40     else
41       raise Puppet::Error, "Failed to destroy replication slot #{resource[:name]}:\n#{output[0]}"
42     end
43   end
44
45   private
46
47   def self.run_sql_command(sql)
48     command = ['psql', '-t', '-c', sql]
49
50     self.run_command(command, 'postgres', 'postgres')
51   end
52
53   def self.run_command(command, user, group)
54     if Puppet::PUPPETVERSION.to_f < 3.4
55       Puppet::Util::SUIDManager.run_and_capture(command, user, group)
56     else
57       output = Puppet::Util::Execution.execute(command, {
58         :uid                => user,
59         :gid                => group,
60         :failonfail         => false,
61         :combine            => true,
62         :override_locale    => true,
63         :custom_environment => {}
64       })
65       [output, $CHILD_STATUS.dup]
66     end
67   end
68 end