| 1 |
# frozen_string_literal: true |
| 2 |
|
| 3 |
module Puppet::Util |
| 4 |
# postgresql_validator.rb |
| 5 |
class PostgresqlValidator |
| 6 |
attr_reader :resource |
| 7 |
|
| 8 |
def initialize(resource) |
| 9 |
@resource = resource |
| 10 |
end |
| 11 |
|
| 12 |
def build_psql_cmd |
| 13 |
cmd = [@resource[:psql_path], '--tuples-only', '--quiet', '--no-psqlrc'] |
| 14 |
|
| 15 |
args = { |
| 16 |
host: '--host', |
| 17 |
port: '--port', |
| 18 |
db_username: '--username', |
| 19 |
db_name: '--dbname', |
| 20 |
command: '--command' |
| 21 |
} |
| 22 |
|
| 23 |
args.each do |k, v| |
| 24 |
if @resource[k] |
| 25 |
cmd.push v |
| 26 |
cmd.push @resource[k] |
| 27 |
end |
| 28 |
end |
| 29 |
|
| 30 |
cmd |
| 31 |
end |
| 32 |
|
| 33 |
def connect_settings |
| 34 |
result = @resource[:connect_settings] || {} |
| 35 |
result['PGPASSWORD'] = @resource[:db_password] if @resource[:db_password] |
| 36 |
result |
| 37 |
end |
| 38 |
|
| 39 |
def attempt_connection(sleep_length, tries) |
| 40 |
(0..tries - 1).each do |_try| |
| 41 |
Puppet.debug "PostgresqlValidator.attempt_connection: Attempting connection to #{@resource[:db_name]}" |
| 42 |
cmd = build_psql_cmd |
| 43 |
Puppet.debug "PostgresqlValidator.attempt_connection: #{cmd.inspect}" |
| 44 |
result = Execution.execute(cmd, custom_environment: connect_settings, uid: @resource[:run_as]) |
| 45 |
|
| 46 |
if result && !result.empty? |
| 47 |
Puppet.debug "PostgresqlValidator.attempt_connection: Connection to #{@resource[:db_name] || connect_settings.select { |elem| elem.include?('PGDATABASE') }} successful!" |
| 48 |
return true |
| 49 |
else |
| 50 |
Puppet.warning "PostgresqlValidator.attempt_connection: Sleeping for #{sleep_length} seconds" |
| 51 |
sleep sleep_length |
| 52 |
end |
| 53 |
end |
| 54 |
false |
| 55 |
end |
| 56 |
end |
| 57 |
end |