ruby.rb 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. Puppet::Type.type(:postgresql_psql).provide(:ruby) do
  2. def run_unless_sql_command(sql)
  3. # for the 'unless' queries, we wrap the user's query in a 'SELECT COUNT',
  4. # which makes it easier to parse and process the output.
  5. run_sql_command('SELECT COUNT(*) FROM (' << sql << ') count')
  6. end
  7. def run_sql_command(sql)
  8. if resource[:search_path]
  9. sql = "set search_path to #{Array(resource[:search_path]).join(',')}; #{sql}"
  10. end
  11. command = [resource[:psql_path]]
  12. command.push("-d", resource[:db]) if resource[:db]
  13. command.push("-p", resource[:port]) if resource[:port]
  14. command.push("-t", "-c", '"' + sql.gsub('"', '\"') + '"')
  15. environment = get_environment
  16. if resource[:cwd]
  17. Dir.chdir resource[:cwd] do
  18. run_command(command, resource[:psql_user], resource[:psql_group], environment)
  19. end
  20. else
  21. run_command(command, resource[:psql_user], resource[:psql_group], environment)
  22. end
  23. end
  24. private
  25. def get_environment
  26. environment = (resource[:connect_settings] || {}).dup
  27. if envlist = resource[:environment]
  28. envlist = [envlist] unless envlist.is_a? Array
  29. envlist.each do |setting|
  30. if setting =~ /^(\w+)=((.|\n)+)$/
  31. env_name = $1
  32. value = $2
  33. if environment.include?(env_name) || environment.include?(env_name.to_sym)
  34. if env_name == 'NEWPGPASSWD'
  35. warning "Overriding environment setting '#{env_name}' with '****'"
  36. else
  37. warning "Overriding environment setting '#{env_name}' with '#{value}'"
  38. end
  39. end
  40. environment[env_name] = value
  41. else
  42. warning "Cannot understand environment setting #{setting.inspect}"
  43. end
  44. end
  45. end
  46. return environment
  47. end
  48. def run_command(command, user, group, environment)
  49. command = command.join ' '
  50. if Puppet::PUPPETVERSION.to_f < 3.0
  51. require 'puppet/util/execution'
  52. Puppet::Util::Execution.withenv environment do
  53. Puppet::Util::SUIDManager.run_and_capture(command, user, group)
  54. end
  55. elsif Puppet::PUPPETVERSION.to_f < 3.4
  56. Puppet::Util.withenv environment do
  57. Puppet::Util::SUIDManager.run_and_capture(command, user, group)
  58. end
  59. else
  60. output = Puppet::Util::Execution.execute(command, {
  61. :uid => user,
  62. :gid => group,
  63. :failonfail => false,
  64. :combine => true,
  65. :override_locale => true,
  66. :custom_environment => environment,
  67. })
  68. [output, $CHILD_STATUS.dup]
  69. end
  70. end
  71. end