Advertisement
Guest User

Untitled

a guest
Sep 20th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. class RestoreLatestBackupToDebugDatabaseJob < ActiveJob::Base
  2. queue_as :default
  3.  
  4. def perform
  5. # Open the S3 bucket
  6. bucket = Aws::S3::Resource.new.bucket(ENV.fetch('PGBACKUPS_BUCKET'))
  7.  
  8. # Get the key of the latest backup
  9. Rails.logger.info "Determining the latest backup"
  10. backup_key = key_of_latest_backup(bucket)
  11.  
  12. # Download and write to a temporary file
  13. backup_path = "#{Dir.tmpdir}/backup_#{backup_key.split('/')[-1]}"
  14. Rails.logger.info "Downloading backup #{backup_key} to #{backup_path}"
  15. bucket.object(backup_key).get(response_target: backup_path)
  16.  
  17. # Import the dump into the debug database
  18. host = ENV.fetch('DEBUG_DB_HOST')
  19. port = ENV.fetch('DEBUG_DB_PORT')
  20. username = ENV.fetch('DEBUG_DB_USERNAME')
  21. database = ENV.fetch('DEBUG_DB_DATABASE')
  22. password = ENV.fetch('DEBUG_DB_PASSWORD')
  23. restore_cmd = "PGPASSWORD=#{password} pg_restore --verbose --clean --no-acl --no-owner -h #{host} -p #{port} -U #{username} -d #{database} #{backup_path}"
  24. Rails.logger.info "Restoring the backup: #{restore_cmd}"
  25. system restore_cmd
  26. end
  27.  
  28. private
  29.  
  30. def key_of_latest_backup(bucket)
  31. # First we get only the metadata of all backups and we select the one that was modified most recently.
  32. latest_object_summary = nil
  33. bucket.objects(prefix: "pgbackups/production/").each do |object_summary|
  34. if latest_object_summary.nil? || latest_object_summary.last_modified < object_summary.last_modified
  35. latest_object_summary = object_summary
  36. end
  37. end
  38.  
  39. # Raise an error if the backup is older than a week ago. Then we have a problem.
  40. if latest_object_summary.last_modified < 1.week.ago
  41. raise "The last database backup is from #{latest_object_summary.last_modified}, which is more than a week ago."
  42. end
  43.  
  44. # Returns its key
  45. return latest_object_summary.key
  46. end
  47. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement