database_config.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/
  2. require 'yaml'
  3. require 'resolv'
  4. cnf = YAML.load_file(File.join(__dir__, '../../config/database/database.yml'))
  5. cnf.delete('default')
  6. database = ENV['ENFORCE_DB_SERVICE']
  7. # Lookup in /etc/hosts first: gitlab uses that if FF_NETWORK_PER_BUILD is not set.
  8. if !database
  9. hostsfile = '/etc/hosts'
  10. database = %w[postgresql mysql].shuffle.find do |possible_database|
  11. File.foreach(hostsfile).any? { |l| l[possible_database] }
  12. end
  13. end
  14. # Lookup via DNS if needed: gitlab uses that if FF_NETWORK_PER_BUILD is enabled.
  15. if !database
  16. dns = Resolv::DNS.new
  17. dns.timeouts = 3
  18. database = %w[postgresql mysql].shuffle.find do |possible_database|
  19. # Perform a lookup of the database host to check if it is configured as a service.
  20. if dns.getaddress possible_database
  21. next possible_database
  22. end
  23. rescue Resolv::ResolvError
  24. # Ignore DNS lookup errors
  25. end
  26. end
  27. raise "Can't find any supported database." if database.nil?
  28. puts "NOTICE: Found/selected #{database} Database Service"
  29. db_settings_map = {
  30. 'postgresql' => {
  31. 'adapter' => 'postgresql',
  32. 'username' => 'zammad',
  33. 'password' => 'zammad',
  34. 'host' => 'postgresql', # db alias from gitlab-ci.yml
  35. },
  36. 'mysql' => {
  37. 'adapter' => 'mysql2',
  38. 'username' => 'root',
  39. 'password' => 'zammad',
  40. 'host' => 'mysql', # db alias from gitlab-ci.yml
  41. }
  42. }
  43. # fetch DB settings from settings map and fallback to postgresql
  44. db_settings = db_settings_map.fetch(database) { db_settings_map['postgresql'] }
  45. %w[development test production].each do |environment|
  46. cnf[environment].merge!(db_settings)
  47. end
  48. File.open('config/database.yml', 'w') do |file|
  49. file.write(Psych.dump(cnf))
  50. end