Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

extract PostgresEnvironment to share between BackupJob and backup rake tasks

Ivan Kuchin98e8fa792a53
diff --git a/app/workers/backup_job.rb b/app/workers/backup_job.rb
index 3db87b42473..4d87468c0b7 100644
--- a/app/workers/backup_job.rb
+++ b/app/workers/backup_job.rb
@@ -30,6 +30,8 @@ require 'tempfile'
require 'zip'
class BackupJob < ApplicationJob
+ include OpenProject::PostgresEnvironment
+
queue_with_priority :above_normal
attr_reader :backup, :user
@@ -258,34 +260,4 @@ class BackupJob < ApplicationJob
message: error.present? ? "#{msg}: #{error}" : msg
)
end
-
- def pg_env
- entries = pg_env_to_connection_config.map do |key, config_key|
- possible_keys = Array(config_key)
- value = possible_keys
- .lazy
- .filter_map { |key| database_config[key] }
- .first
-
- [key.to_s, value.to_s] if value.present?
- end
-
- entries.compact.to_h
- end
-
- def database_config
- @database_config ||= ActiveRecord::Base.connection_db_config.configuration_hash
- end
-
- ##
- # Maps the PG env variable name to the key in the AR connection config.
- def pg_env_to_connection_config
- {
- PGHOST: :host,
- PGPORT: :port,
- PGUSER: %i[username user],
- PGPASSWORD: :password,
- PGDATABASE: :database
- }
- end
end
diff --git a/lib/open_project/postgres_environment.rb b/lib/open_project/postgres_environment.rb
new file mode 100644
index 00000000000..32f92bec66b
--- /dev/null
+++ b/lib/open_project/postgres_environment.rb
@@ -0,0 +1,59 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2024 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See COPYRIGHT and LICENSE files for more details.
+#++
+
+module OpenProject
+ module PostgresEnvironment
+ ##
+ # Maps the PG env variable name to the key in the AR connection config.
+ PG_ENV_TO_CONNECTION_CONFIG = {
+ PGHOST: :host,
+ PGPORT: :port,
+ PGUSER: %i[username user],
+ PGPASSWORD: :password,
+ PGDATABASE: :database
+ }.freeze
+
+ module_function
+
+ def pg_env
+ database_config = ActiveRecord::Base.connection_db_config.configuration_hash
+
+ entries = PG_ENV_TO_CONNECTION_CONFIG.map do |key, config_key|
+ possible_keys = Array(config_key)
+ value = possible_keys
+ .lazy
+ .filter_map { |key| database_config[key] }
+ .first
+
+ [key.to_s, value.to_s] if value.present?
+ end
+
+ entries.compact.to_h
+ end
+ end
+end
diff --git a/lib/tasks/backup.rake b/lib/tasks/backup.rake
index fc10ce6e396..63b8329463f 100644
--- a/lib/tasks/backup.rake
+++ b/lib/tasks/backup.rake
@@ -36,25 +36,17 @@ namespace :backup do
args.with_defaults(path_to_backup: default_db_filename)
Pathname(args[:path_to_backup]).dirname.mkpath
- config = database_configuration
+ include OpenProject::PostgresEnvironment
- pg_dump_call = ['pg_dump',
- '--clean',
- "--file=#{args[:path_to_backup]}",
- '--format=custom',
- '--no-owner']
- pg_dump_call << "--host=#{config[:host]}" if config[:host]
- pg_dump_call << "--port=#{config[:port]}" if config[:port]
- pg_dump_call << "--username=#{config[:user]}" if config[:user]
- pg_dump_call << config[:database].to_s
+ pg_dump_call = %W[
+ pg_dump
+ --clean
+ --file=#{args[:path_to_backup]}
+ --format=custom
+ --no-owner
+ ]
- if config[:password]
- with_config_file(config) do |config_file|
- Kernel.system({ 'PGPASSFILE' => config_file }, *pg_dump_call)
- end
- else
- Kernel.system(*pg_dump_call)
- end
+ Kernel.system(pg_env, *pg_dump_call)
end
desc 'Restores a database dump created by the :create task.'
@@ -62,46 +54,24 @@ namespace :backup do
raise 'You must provide the path to the database dump' unless args[:path_to_backup]
raise "File '#{args[:path_to_backup]}' is not readable" unless File.readable?(args[:path_to_backup])
- config = database_configuration
+ include OpenProject::PostgresEnvironment
- pg_restore_call = ['pg_restore',
- '--clean',
- '--no-owner',
- '--single-transaction',
- "--dbname=#{config[:database]}"]
- pg_restore_call << "--host=#{config[:host]}" if config[:host]
- pg_restore_call << "--port=#{config[:port]}" if config[:port]
- pg_restore_call << "--username=#{config[:user]}" if config[:user]
- pg_restore_call << args[:path_to_backup].to_s
+ # PGDATABASE is ignored by pg_restore if not specified explicitly
+ # https://www.postgresql.org/docs/current/app-pgrestore.html#:~:text=PGDATABASE
+ pg_restore_call = %W[
+ pg_restore
+ --clean
+ --no-owner
+ --single-transaction
+ --dbname=#{pg_env['PGDATABASE']}
+ #{args[:path_to_backup]}
+ ]
- if config[:password]
- with_config_file(config) do |config_file|
- Kernel.system({ 'PGPASSFILE' => config_file }, *pg_restore_call)
- end
- else
- Kernel.system(*pg_restore_call)
- end
+ Kernel.system(pg_env, *pg_restore_call)
end
private
- def database_configuration
- hash = ActiveRecord::Base.connection_db_config.configuration_hash
-
- {
- **hash.slice(:host, :port, :database, :password),
- user: hash[:user] || hash[:username],
- }
- end
-
- def with_config_file(config, &blk)
- Tempfile.open('op_pg_config') do |file|
- file.write "*:*:*:*:#{config[:password]}"
- file.close
- blk.yield file.path
- end
- end
-
def default_db_filename
filename = "openproject-#{Rails.env}-db-#{date_string}.backup"
Rails.root.join('backup', sanitize_filename(filename))
diff --git a/spec/tasks/backup_spec.rb b/spec/tasks/backup_spec.rb
index feece39c4bf..c39a27b59a1 100644
--- a/spec/tasks/backup_spec.rb
+++ b/spec/tasks/backup_spec.rb
@@ -56,16 +56,11 @@ RSpec.describe Rake::Task, 'backup:database' do
end
end
- it 'writes the pg password file' do
- # can't use have_received because password file is deleted after invocation
- expect(Kernel).to receive(:system) do |*args| # rubocop:disable RSpec/MessageSpies
- pass_file = args.first['PGPASSFILE']
- expect(File.readable?(pass_file)).to be true
-
- file_contents = File.read pass_file
- expect(file_contents).to include('test_password')
- end
+ it 'passes environment variables to the binary' do
subject.invoke
+ expect(Kernel).to have_received(:system) do |*args|
+ expect(args[0]).to include('PGUSER' => 'test_user', 'PGPASSWORD' => 'test_password')
+ end
end
it 'uses the first task parameter as the target filename' do
@@ -96,16 +91,11 @@ RSpec.describe Rake::Task, 'backup:database' do
end
end
- it 'writes the pg password file' do
- # can't use have_received because password file is deleted after invocation
- expect(Kernel).to receive(:system) do |*args| # rubocop:disable RSpec/MessageSpies
- pass_file = args.first['PGPASSFILE']
- expect(File.readable?(pass_file)).to be true
-
- file_contents = File.read pass_file
- expect(file_contents).to include('test_password')
- end
+ it 'passes environment variables to the binary' do
subject.invoke backup_file.path
+ expect(Kernel).to have_received(:system) do |*args|
+ expect(args[0]).to include('PGUSER' => 'test_user', 'PGPASSWORD' => 'test_password')
+ end
end
it 'uses the first task parameter as the target filename' do
@@ -115,6 +105,13 @@ RSpec.describe Rake::Task, 'backup:database' do
end
end
+ it 'specifies database name' do
+ subject.invoke backup_file.path
+ expect(Kernel).to have_received(:system) do |*args|
+ expect(args).to include '--dbname=openproject-database'
+ end
+ end
+
it 'throws an error when called without a parameter' do
expect { subject.invoke }.to raise_error(RuntimeError, "You must provide the path to the database dump")
end
diff --git a/spec/workers/backup_job_spec.rb b/spec/workers/backup_job_spec.rb
index c843b5f0f8f..1fc7438efb1 100644
--- a/spec/workers/backup_job_spec.rb
+++ b/spec/workers/backup_job_spec.rb
@@ -85,8 +85,33 @@ RSpec.describe BackupJob, type: :model do
job.perform **arguments.first
end
- describe '#pg_env' do
- subject { job.pg_env }
+ describe 'environment variables' do
+ let(:hash_config) do
+ ActiveRecord::DatabaseConfigurations::HashConfig.new('test', 'primary', config_double)
+ end
+
+ before do
+ allow(ActiveRecord::Base).to receive(:connection_db_config).and_return(hash_config)
+ end
+
+ context 'when config has username' do
+ let(:config_double) do
+ {
+ adapter: :postgresql,
+ password: "blabla",
+ database: "test",
+ username: "foobar"
+ }
+ end
+
+ it 'sets PGUSER and other variables' do
+ perform
+
+ expect(Open3).to have_received(:capture3) do |*args|
+ expect(args[0]).to include('PGUSER' => 'foobar', 'PGPASSWORD' => 'blabla', 'PGDATABASE' => 'test')
+ end
+ end
+ end
context 'when config has user reference, not username (regression #44251)' do
let(:config_double) do
@@ -98,14 +123,12 @@ RSpec.describe BackupJob, type: :model do
}
end
- before do
- allow(job).to receive(:database_config).and_return(config_double)
- end
+ it 'still sets PGUSER and other variables' do
+ perform
- it 'still sets a PGUSER' do
- expect(subject['PGUSER']).to eq 'foobar'
- expect(subject['PGPASSWORD']).to eq 'blabla'
- expect(subject['PGDATABASE']).to eq 'test'
+ expect(Open3).to have_received(:capture3) do |*args|
+ expect(args[0]).to include('PGUSER' => 'foobar', 'PGPASSWORD' => 'blabla', 'PGDATABASE' => 'test')
+ end
end
end
end