Skip to content

Instantly share code, notes, and snippets.

@edshadi
Created February 10, 2012 18:38
Show Gist options
  • Save edshadi/1791538 to your computer and use it in GitHub Desktop.
Save edshadi/1791538 to your computer and use it in GitHub Desktop.
mongo and mysql backup to s3 script
#!/usr/bin/env ruby
ENV["RAILS_ENV"] ||= "development"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 's3_file_methods'
require "fileutils"
def run(command)
result = system(command)
raise("error, process exited with status #{$?.exitstatus}") unless result
end
def mysql_backup
begin
db_config = get_configs_for('mysql')
mysql_database = db_config[:database]
mysql_user = db_config[:username]
mysql_password = db_config[:password]
temp_dir = "/tmp/mysql-backup"
FileUtils.mkdir_p temp_dir
backup_dir = "mysql-backup"
dump_file = "#{Time.now.to_i}-dump.sql.gz"
cmd = "mysqldump -u#{mysql_user}"
cmd += " -p'#{mysql_password}'" unless mysql_password.nil?
cmd += " #{mysql_database} | gzip > #{temp_dir}/#{dump_file}"
run(cmd)
S3FileMethods.write_file "#{backup_dir}/#{dump_file}", open("#{temp_dir}/#{dump_file}"), {:access => :private}, {:use_ssl => true}
ensure
FileUtils.rm_rf(temp_dir)
end
end
def mongo_backup
begin
temp_dir = "dump"
db_config = get_configs_for('mongo')
mongo_database = db_config[:database]
backup_dir = "mongo-backup"
dump_file = "#{Time.now.to_i}-dump.tar.gz"
run("mongodump -d #{mongo_database}")
run("tar -czf #{dump_file} #{temp_dir}")
S3FileMethods.write_file "#{backup_dir}/#{dump_file}", open("#{dump_file}"), {:access => :private}, {:use_ssl => true}
ensure
FileUtils.rm_rf(temp_dir)
FileUtils.rm_rf(dump_file)
end
end
def get_configs_for(db)
yamlFile = YAML.load_file("#{Rails.root}/config/#{db == 'mysql' ? 'database.yml' : 'mongo.yml'}")
yamlFile[Rails.env].symbolize_keys
end
mysql_backup
mongo_backup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment