Created
February 2, 2011 20:54
-
-
Save kevinansfield/808409 to your computer and use it in GitHub Desktop.
automated heroku pgbackups
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
require 'net/http' | |
require 'uri' | |
require 'heroku' | |
require 'heroku/command' | |
require 'heroku/commands/pgbackups' | |
require 'pgbackups/client' | |
namespace :backup do | |
def upload!(backup_url, s3_access_policy, object_prefix='') | |
puts "[#{Time.now}] backup:database beginning upload to s3" | |
object_name = "#{object_prefix}#{@heroku_app}_#{Time.now.xmlschema}.dump" | |
options = {'z-amz-acl' => s3_access_policy} | |
url = URI.parse(backup_url) | |
backup_data = Net::HTTP.get_response(url).body | |
response = @storage.put_object(@s3_bucket, object_name, backup_data, options) | |
end | |
desc 'Backup postgres database to S3' | |
task 'database' => :environment do | |
puts "[#{Time.now}] backup:database started" | |
begin | |
#S3 config | |
@s3_access_key_id = ENV['S3_ACCESS_KEY'] | |
@s3_secret_access_key = ENV['S3_SECRET_ACCESS_KEY'] | |
@s3_bucket = ENV['S3_BACKUP_BUCKET'] | |
#Heroku config | |
@heroku_app = ENV['HEROKU_APP'] | |
@heroku_user = ENV['HEROKU_USER'] | |
@heroku_pass = ENV['HEROKU_PASS'] | |
@storage = Fog::Storage.new( | |
:provider => 'AWS', | |
:aws_access_key_id => @s3_access_key_id, | |
:aws_secret_access_key => @s3_secret_access_key | |
) | |
# backup, auto-expiring oldest backup | |
pgbackups_client = PGBackups::Client.new(ENV["PGBACKUPS_URL"]) | |
pgbackups_client.create_transfer(ENV['SHARED_DATABASE_URL'], ENV['DATABASE_URL'], nil, 'BACKUP', :expire => true) | |
# get latest pgbackup | |
heroku = Heroku::Client.new(@heroku_user, @heroku_pass) | |
@args = @heroku_app.blank? ? [] : ["--app", @heroku_app] | |
pg_backup = Heroku::Command::Pgbackups.new(@args, heroku) | |
backup_url = pg_backup.pgbackup_client.get_latest_backup['public_url'] | |
backup_url.strip unless backup_url.blank? | |
upload!(backup_url, 'private', 'database/') | |
puts "[#{Time.now}] backup:database complete" | |
rescue Exception => e | |
if ENV['HOPTOAD_KEY'] | |
require 'toadhopper' | |
Toadhopper(ENV['HOPTOAD_KEY']).post!(e) | |
else | |
puts "[#{Time.now}] backup:database error: #{e}" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment