Created
February 27, 2014 21:13
-
-
Save rajeevkannav/9259691 to your computer and use it in GitHub Desktop.
mysqldump
This file contains hidden or 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 :mysql do | |
desc "simple mysql db dump" + | |
'Can be used as rake mysql:dumpher[backup_location, expected_dumpfile_size, email_notification_required]' + | |
'For e.g In My case rake mysql:dumpher[/home/rajeev/Public,20,true] RAILS_ENV=production' | |
task :dumpher, [:target_bucket, :expected_dump_size, :notify] => [:environment] do |t, args| | |
args.with_defaults(host: 'localhost', target_bucket: '/', expected_dump_size: 25) | |
_db_config = ActiveRecord::Base.configurations[Rails.env] | |
_db = _db_config['database'] | |
file = "#{_db}_#{Time.now.strftime('%Y_%m_%d_%H_%M_%S')}.sql.gz" | |
_host = _db_config['host'].nil? ? 'localhost' : _db_config['host'] | |
start_time = Time.now | |
`mysqldump --host=#{_host} -u #{_db_config['username']} -p#{_db_config['password']} #{_db} | gzip > #{args.target_bucket}/#{file}` | |
status = (File.size("#{args.target_bucket}/#{file}") > args.expected_dump_size.to_i) ? 'success' : 'failure' | |
total_time = Time.at(Time.now-start_time).gmtime.strftime('%R:%S') | |
MysqlDumperMailer.backup_success(status, _db, total_time, args.target_bucket).deliver! if args.notify == 'true' | |
end | |
end | |
class MysqlDumperMailer < ActionMailer::Base | |
default from: 'Sysadmin <[email protected]>' | |
def backup_success(status, database, total_time, target_bucket) | |
subject = { | |
success: "Mysql dump for database #{database} completed [#{Time.now}]", | |
failure: "Urgent: Mysql dump for database #{database} Failed #{Time.now}" | |
} | |
body = { | |
success: "<b>Moved database dump to Location: #{target_bucket} in #{total_time}.</b><br /> | |
You can view them in the #{target_bucket} location on the sever", | |
failure: "<b>Something Nasty happend while backup database</b>." | |
} | |
mail(to: '[email protected]', subject: subject[status.to_sym], :body => body[status.to_sym], :content_type => 'text/html') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment