Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class RestoreLatestBackupToDebugDatabaseJob < ActiveJob::Base
- queue_as :default
- def perform
- # Open the S3 bucket
- bucket = Aws::S3::Resource.new.bucket(ENV.fetch('PGBACKUPS_BUCKET'))
- # Get the key of the latest backup
- Rails.logger.info "Determining the latest backup"
- backup_key = key_of_latest_backup(bucket)
- # Download and write to a temporary file
- backup_path = "#{Dir.tmpdir}/backup_#{backup_key.split('/')[-1]}"
- Rails.logger.info "Downloading backup #{backup_key} to #{backup_path}"
- bucket.object(backup_key).get(response_target: backup_path)
- # Import the dump into the debug database
- host = ENV.fetch('DEBUG_DB_HOST')
- port = ENV.fetch('DEBUG_DB_PORT')
- username = ENV.fetch('DEBUG_DB_USERNAME')
- database = ENV.fetch('DEBUG_DB_DATABASE')
- password = ENV.fetch('DEBUG_DB_PASSWORD')
- restore_cmd = "PGPASSWORD=#{password} pg_restore --verbose --clean --no-acl --no-owner -h #{host} -p #{port} -U #{username} -d #{database} #{backup_path}"
- Rails.logger.info "Restoring the backup: #{restore_cmd}"
- system restore_cmd
- end
- private
- def key_of_latest_backup(bucket)
- # First we get only the metadata of all backups and we select the one that was modified most recently.
- latest_object_summary = nil
- bucket.objects(prefix: "pgbackups/production/").each do |object_summary|
- if latest_object_summary.nil? || latest_object_summary.last_modified < object_summary.last_modified
- latest_object_summary = object_summary
- end
- end
- # Raise an error if the backup is older than a week ago. Then we have a problem.
- if latest_object_summary.last_modified < 1.week.ago
- raise "The last database backup is from #{latest_object_summary.last_modified}, which is more than a week ago."
- end
- # Returns its key
- return latest_object_summary.key
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement