d737f12a891943898ab9b2aee3ff2ac722ae8482
[mirror/dsa-puppet.git] / 3rdparty / modules / postgresql / lib / puppet / util / postgresql_validator.rb
1 module Puppet
2   module Util
3     class PostgresqlValidator
4       attr_reader :resource
5
6       def initialize(resource)
7         @resource = resource
8       end
9
10       def build_psql_cmd
11         final_cmd = []
12
13         cmd_init = "#{@resource[:psql_path]} --tuples-only --quiet --no-psqlrc"
14
15         final_cmd.push cmd_init
16
17         cmd_parts = {
18           :host => "--host #{@resource[:host]}",
19           :port => "--port #{@resource[:port]}",
20           :db_username => "--username #{@resource[:db_username]}",
21           :db_name => "--dbname #{@resource[:db_name]}",
22           :command => "--command '#{@resource[:command]}'"
23         }
24
25         cmd_parts.each do |k,v|
26           final_cmd.push v if @resource[k]
27         end
28
29         final_cmd.join ' '
30       end
31
32       def parse_connect_settings
33         c_settings = @resource[:connect_settings] || {}
34         c_settings.merge! ({ 'PGPASSWORD' => @resource[:db_password] }) if @resource[:db_password]
35         return c_settings.map { |k,v| "#{k}=#{v}" }
36       end
37
38       def attempt_connection(sleep_length, tries)
39         (0..tries-1).each do |try|
40           Puppet.debug "PostgresqlValidator.attempt_connection: Attempting connection to #{@resource[:db_name]}"
41           Puppet.debug "PostgresqlValidator.attempt_connection: #{build_validate_cmd}"
42           result = execute_command
43           if result && result.length > 0
44             Puppet.debug "PostgresqlValidator.attempt_connection: Connection to #{@resource[:db_name] || parse_connect_settings.select { |elem| elem.match /PGDATABASE/ }} successful!"
45             return true
46           else
47             Puppet.warning "PostgresqlValidator.attempt_connection: Sleeping for #{sleep_length} seconds"
48             sleep sleep_length
49           end
50         end
51         false
52       end
53
54       private
55
56       def execute_command
57         Execution.execute(build_validate_cmd, :uid => @resource[:run_as])
58       end
59
60       def build_validate_cmd
61         "#{parse_connect_settings.join(' ')} #{build_psql_cmd} "
62       end
63     end
64   end
65 end