Created
August 26, 2012 03:40
-
-
Save Epictetus/3473649 to your computer and use it in GitHub Desktop.
Simple cron job for Heroku to back up your database to S3 and remove stale database sessions.
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
task :cron => :environment do | |
# removes day old sessions from the database | |
puts "====> Removing stale sessions from the database…” | |
Rake::Task['db:sessions:clear_stale'].execute | |
# run the following tasks on sunday | |
if Time.now.wday == 0 | |
# backs up the database to S3 | |
puts "====> Backing up database to S3…” | |
Rake::Task['db:backup'].invoke | |
end | |
end |
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
namespace :db do | |
desc "Backs up the database to S3" | |
task :backup => :environment do | |
puts "Back up started on #{Time.now}..." | |
PATH_TO_CLIENT_BACKUP = 'specific-path-in-bucket' | |
puts "Pulling database..." | |
backup_name = "ew#{Time.now.to_i}.db" | |
backup_path = "tmp/#{backup_name}" | |
YamlDb.dump backup_path | |
puts "Compressing database..." | |
'gzip #{backup_path}' | |
backup_name += ".gz" | |
backup_path = "tmp/#{backup_name}" | |
puts "Uploading #{backup_name} to S3..." | |
puts "Connecting to AWS..." | |
config = YAML.load(File.open("#{RAILS_ROOT}/config/s3.yml"))[RAILS_ENV] | |
AWS::S3::Base.establish_connection!( | |
:access_key_id => config['access_key_id'], | |
:secret_access_key => config['secret_access_key'] | |
) | |
puts "Finding S3 bucket..." | |
begin | |
bucket = AWS::S3::Bucket.find config['bucket'] | |
rescue AWS::S3::NoSuchBucket | |
AWS::S3::Bucket.create config['bucket'] | |
bucket = AWS::S3::Bucket.find config['bucket'] | |
end | |
puts "Storing backup database on S3..." | |
AWS::S3::S3Object.store backup_name, | |
File.read(backup_path), | |
bucket.name + PATH_TO_CLIENT_BACKUP, | |
:content_type => 'application/x-gzip' | |
puts "Backup ended on #{Time.now}" | |
end | |
end |
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
namespace :db do | |
namespace :sessions do | |
desc "Clears stale (e.g. day old) sessions" | |
task :clear_stale => :environment do | |
session_count = ActiveRecord::SessionStore::Session.delete_all(['updated_at < ?', 1.day.ago]) | |
puts "#{session_count} sessions removed..." | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment