Skip to content

A platform for community discussion. Free, open, simple.

DEV: Harden TemporaryDb for reliability and parallel safety (#37881)

Gerhard Schlager5a5d5aaea3fc
diff --git a/lib/tasks/db.rake b/lib/tasks/db.rake
index 3b0225a3157..5fd71e00f9f 100644
--- a/lib/tasks/db.rake
+++ b/lib/tasks/db.rake
@@ -386,32 +386,35 @@ end
desc "Validate indexes"
task "db:validate_indexes", [:arg] => %w[db:ensure_post_migrations environment] do |_, args|
- db = TemporaryDb.new
- db.start
- db.migrate
-
- ActiveRecord::Base.establish_connection(
- adapter: "postgresql",
- database: "discourse",
- port: db.pg_port,
- host: "localhost",
- )
-
- expected = DB.query_single <<~SQL
- SELECT indexdef FROM pg_indexes
- WHERE schemaname = 'public'
- ORDER BY indexdef
- SQL
+ begin
+ db = TemporaryDb.new
+ db.start
+ db.migrate
+
+ ActiveRecord::Base.establish_connection(
+ adapter: "postgresql",
+ database: "discourse",
+ port: db.pg_port,
+ host: "localhost",
+ )
- expected_tables = DB.query_single <<~SQL
- SELECT tablename
- FROM pg_tables
- WHERE schemaname = 'public'
- SQL
+ expected = DB.query_single <<~SQL
+ SELECT indexdef FROM pg_indexes
+ WHERE schemaname = 'public'
+ ORDER BY indexdef
+ SQL
- ActiveRecord::Base.establish_connection
+ expected_tables = DB.query_single <<~SQL
+ SELECT tablename
+ FROM pg_tables
+ WHERE schemaname = 'public'
+ SQL
- db.stop
+ ActiveRecord::Base.establish_connection
+ ensure
+ db&.stop
+ db&.remove
+ end
puts
diff --git a/lib/temporary_db.rb b/lib/temporary_db.rb
index 96e2fe261f1..98f08e44bef 100644
--- a/lib/temporary_db.rb
+++ b/lib/temporary_db.rb
@@ -1,9 +1,19 @@
# frozen_string_literal: true
+require "open3"
+require "securerandom"
+require "tmpdir"
+
class TemporaryDb
- PG_TEMP_PATH = "/tmp/pg_schema_tmp"
- PG_CONF = "#{PG_TEMP_PATH}/postgresql.conf"
- PG_SOCK_PATH = "#{PG_TEMP_PATH}/sockets"
+ PG_TEMP_PREFIX = "pg_schema_tmp"
+ VERSIONS = 10..30 # arbitrary upper limit to avoid updating this code for a long time
+ STARTUP_TIMEOUT_SECONDS = 60
+
+ def initialize
+ @pg_temp_path = File.join(Dir.tmpdir, "#{PG_TEMP_PREFIX}_#{SecureRandom.hex(6)}")
+ @pg_conf = "#{@pg_temp_path}/postgresql.conf"
+ @pg_sock_path = "#{@pg_temp_path}/sockets"
+ end
def port_available?(port)
TCPServer.open(port).close
@@ -15,31 +25,27 @@ class TemporaryDb
def pg_bin_path
return @pg_bin_path if @pg_bin_path
- %w[13 12 11 10].each do |v|
+ # Debian/Ubuntu: /usr/lib/postgresql/{version}/bin
+ VERSIONS.reverse_each do |v|
bin_path = "/usr/lib/postgresql/#{v}/bin"
- if File.exist?("#{bin_path}/pg_ctl")
- @pg_bin_path = bin_path
- break
- end
+ return @pg_bin_path = bin_path if File.exist?("#{bin_path}/pg_ctl")
end
- if !@pg_bin_path
- bin_path = "/Applications/Postgres.app/Contents/Versions/latest/bin"
- @pg_bin_path = bin_path if File.exist?("#{bin_path}/pg_ctl")
- end
- if !@pg_bin_path
- puts "Can not find postgres bin path"
- exit 1
+
+ # RHEL/Fedora (PGDG): /usr/pgsql-{version}/bin
+ VERSIONS.reverse_each do |v|
+ bin_path = "/usr/pgsql-#{v}/bin"
+ return @pg_bin_path = bin_path if File.exist?("#{bin_path}/pg_ctl")
end
- @pg_bin_path
- end
- def initdb_path
- return @initdb_path if @initdb_path
+ # macOS Postgres.app
+ bin_path = "/Applications/Postgres.app/Contents/Versions/latest/bin"
+ return @pg_bin_path = bin_path if File.exist?("#{bin_path}/pg_ctl")
- @initdb_path = `which initdb 2> /dev/null`.strip
- @initdb_path = "#{pg_bin_path}/initdb" if @initdb_path.length == 0
+ raise "Cannot find pg_ctl. Install the PostgreSQL server package."
+ end
- @initdb_path
+ def initdb_path
+ @initdb_path ||= "#{pg_bin_path}/initdb"
end
def find_free_port(range)
@@ -51,40 +57,34 @@ class TemporaryDb
end
def pg_ctl_path
- return @pg_ctl_path if @pg_ctl_path
-
- @pg_ctl_path = `which pg_ctl 2> /dev/null`.strip
- @pg_ctl_path = "#{pg_bin_path}/pg_ctl" if @pg_ctl_path.length == 0
-
- @pg_ctl_path
+ @pg_ctl_path ||= "#{pg_bin_path}/pg_ctl"
end
def start
- FileUtils.rm_rf PG_TEMP_PATH
- `#{initdb_path} -D '#{PG_TEMP_PATH}' --auth-host=trust --locale=en_US.UTF-8 -E UTF8 2> /dev/null`
-
- FileUtils.mkdir PG_SOCK_PATH
- conf = File.read(PG_CONF)
- File.write(PG_CONF, conf + "\nport = #{pg_port}\nunix_socket_directories = '#{PG_SOCK_PATH}'")
+ init_data_directory
+ configure_ports
puts "Starting postgres on port: #{pg_port}"
+ @previous_discourse_pg_port = ENV["DISCOURSE_PG_PORT"]
ENV["DISCOURSE_PG_PORT"] = pg_port.to_s
- Thread.new { `#{pg_ctl_path} -D '#{PG_TEMP_PATH}' start` }
-
- puts "Waiting for PG server to start..."
- sleep 0.1 while !`#{pg_ctl_path} -D '#{PG_TEMP_PATH}' status`.include?("server is running")
+ start_server
@started = true
- `createuser -h localhost -p #{pg_port} -s -D -w discourse 2> /dev/null`
- `createdb -h localhost -p #{pg_port} discourse`
+ create_user
+ create_database
puts "PG server is ready and DB is loaded"
+ rescue StandardError
+ restore_discourse_pg_port
+ raise
end
def stop
@started = false
- `#{pg_ctl_path} -D '#{PG_TEMP_PATH}' stop`
+ `#{pg_ctl_path} -D '#{@pg_temp_path}' stop`
+ ensure
+ restore_discourse_pg_port
end
def with_env(&block)
@@ -111,7 +111,7 @@ class TemporaryDb
def remove
raise "Error: the database must be stopped before it can be removed" if @started
- FileUtils.rm_rf PG_TEMP_PATH
+ FileUtils.rm_rf @pg_temp_path
end
def migrate
@@ -136,4 +136,86 @@ class TemporaryDb
$stdout.reopen(old_stdout) if old_stdout
$stderr.reopen(old_stderr) if old_stderr
end
+
+ private
+
+ def init_data_directory
+ FileUtils.rm_rf @pg_temp_path
+ run_command!(
+ initdb_path,
+ "-D",
+ @pg_temp_path,
+ "--auth-host=trust",
+ "--locale=en_US.UTF-8",
+ "-E",
+ "UTF8",
+ error_prefix: "Failed to initialize postgres data directory",
+ )
+ end
+
+ def configure_ports
+ FileUtils.mkdir(@pg_sock_path)
+ conf = File.read(@pg_conf)
+ File.write(@pg_conf, conf + "\nport = #{pg_port}\nunix_socket_directories = '#{@pg_sock_path}'")
+ end
+
+ def start_server
+ log_file = File.join(@pg_temp_path, "server.log")
+ run_command!(
+ pg_ctl_path,
+ "-D",
+ @pg_temp_path,
+ "-l",
+ log_file,
+ "-w",
+ "-t",
+ STARTUP_TIMEOUT_SECONDS.to_s,
+ "start",
+ error_prefix: "Failed to start postgres within #{STARTUP_TIMEOUT_SECONDS}s",
+ )
+ end
+
+ def create_user
+ run_command!(
+ "createuser",
+ "-h",
+ "localhost",
+ "-p",
+ pg_port.to_s,
+ "-s",
+ "-D",
+ "-w",
+ "discourse",
+ error_prefix: "Failed to create temporary postgres superuser",
+ )
+ end
+
+ def create_database
+ run_command!(
+ "createdb",
+ "-h",
+ "localhost",
+ "-p",
+ pg_port.to_s,
+ "discourse",
+ error_prefix: "Failed to create temporary postgres database",
+ )
+ end
+
+ def run_command!(*args, error_prefix:)
+ stdout, stderr, status = Open3.capture3(*args)
+ return if status.success?
+
+ details = stderr.to_s.strip
+ details = stdout.to_s.strip if details.empty?
+ details = "unknown error" if details.empty?
+ raise "#{error_prefix}: #{details}"
+ rescue Errno::ENOENT => e
+ raise "#{error_prefix}: #{e.message}"
+ end
+
+ def restore_discourse_pg_port
+ ENV["DISCOURSE_PG_PORT"] = @previous_discourse_pg_port
+ @previous_discourse_pg_port = nil
+ end
end