Skip to content

Instantly share code, notes, and snippets.

@mdub
Created May 12, 2011 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdub/968089 to your computer and use it in GitHub Desktop.
Save mdub/968089 to your computer and use it in GitHub Desktop.
Rake tasks to capture backups and archive in S3
# Tasks designed to run ON Heroku
namespace :pgbackup do
def pgbackup_client
require "pgbackups/client"
@pgbackup_client ||= PGBackups::Client.new(ENV.fetch("PGBACKUPS_URL"))
end
task :capture do
db = "DATABASE_URL"
db_url = ENV.fetch(db)
print "Capturing a database backup ..."
backup = pgbackup_client.create_transfer(db_url, db, nil, "BACKUP", :expire => true)
while true
break if backup["finished_at"]
print "."
sleep 1
backup = pgbackup_client.get_transfer(backup["id"])
end
puts "\n #{backup["to_url"]}"
end
task :archive do
require 'aws/s3'
s3_bucket = ENV.fetch('AWS_S3_BUCKET')
AWS::S3::Base.establish_connection!(
:access_key_id => ENV.fetch('AWS_ACCESS_KEY'),
:secret_access_key => ENV.fetch('AWS_SECRET_KEY')
)
latest_backup = pgbackup_client.get_latest_backup
backup_name = File.basename(latest_backup["to_url"])
backup_url = latest_backup["public_url"]
puts "Downloading #{backup_url}"
backup_data = Net::HTTP.get_response(URI.parse(backup_url)).body
backup_archive_path = "pgbackups/#{backup_name}"
puts "Uploading to S3: /#{s3_bucket}/#{backup_archive_path}"
AWS::S3::S3Object.store(backup_archive_path, backup_data, s3_bucket)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment