database_config.rb 1.7 KB

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