Skip to content

Instantly share code, notes, and snippets.

@lmarburger
Created December 13, 2010 21:54
Show Gist options
  • Save lmarburger/739654 to your computer and use it in GitHub Desktop.
Save lmarburger/739654 to your computer and use it in GitHub Desktop.
Copy the latest Heroku pgdump to S3 and capture a new one
# pgbackups client from heroku gem
require 'pgbackups/client'
desc 'Backup database'
task(:backup_database => :environment) { backup_database }
desc 'cron'
task :cron => :backup_database
def backup_database
store_latest_backup
capture_new_backup
puts 'Done'
rescue Exception => e
report_exception e
end
def client
@client ||= PGBackups::Client.new ENV['PGBACKUPS_URL']
end
def latest_backup_url
@latest_backup_url ||= client.get_latest_backup['public_url']
end
def store_latest_backup
uri = URI.parse latest_backup_url
filename = Pathname.new(uri.path).basename
tmp = Tempfile.new filename
Net::HTTP.start(uri.host) do |http|
puts "Downloading #{ latest_backup_url } to #{ tmp.path }"
http.get [ uri.path, uri.query ].join('?') do |chunk|
tmp.write chunk
end
tmp.rewind
puts "Storing #{ filename }"
# S3Object#store hates being handed a non-String
AWS::S3::S3Object.store filename.to_s, tmp, 'cloudapp-pgbackups'
end
ensure
tmp.close!
end
def capture_new_backup
from_name = 'DATABASE_URL'
from_url = ENV[from_name]
to_name = 'BACKUP'
to_url = nil
puts 'Capturing new backup'
client.create_transfer from_url, from_name, to_url, to_name, :expire => true
end
def report_exception(e)
puts "Backup fail: #{ e.inspect }"
Toadhopper(ENV['HOPTOAD_KEY']).post!(e)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment