Last active
September 24, 2016 20:22
-
-
Save YoranBrondsema/6bb064d46f0bd94c2bb2d9f8dea40ad9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: "DIRECTORY").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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment