Skip to content

Instantly share code, notes, and snippets.

@jalberto
Last active December 19, 2015 02:58
Show Gist options
  • Save jalberto/5886280 to your computer and use it in GitHub Desktop.
Save jalberto/5886280 to your computer and use it in GitHub Desktop.
Simple Backup script
# m h dom mon dow command
0 2 * * * ruby /path/to/db_backup.rb -d -e production -t dayly
0 2 * * 1 ruby /path/to/db_backup.rb -d -e production -t weekly
#!/usr/bin/ruby
# encoding: UTF-8
# vim: set sw=2 sts=2 tw=80 :
require 'optparse'
require 'optparse/time'
require 'yaml'
require 'pp'
VERSION = '0.1'
AUTHOR = 'JoséAlberto <[email protected]>'
BAK_DIR = ENV['HOME'] + "/DB_BAK"
TIMESTAMP = Time.now.strftime("%Y-%m-%d_%H-%M")
# Default Arguments
options = {}
options[:env] = ENV['RAILS_ENV'] || 'development'
options[:type] = :dayly
options[:cleanup] = -1
## Get Arguments
opt_parser = OptionParser.new do |opts|
opts.banner = "Usage: db_backup.rb [--dump][--restore FILE] [--env ENVIRONMENT] [--verbose] [--cleanup DAYS]"
opts.separator ""
opts.separator "For simplicity options are defined in the script."
opts.on("-d", "--dump", "Dump DataBase") do |d|
options[:dump] = d
end
opts.on("-r", "--restore FILE", "Restore DataBase") do |r|
options[:restore] = r
end
opts.on("-c", "--cleanup DAYS", Integer, "Clean files older than DAYS") do |c|
options[:cleanup] = c
end
opts.on("-e", "--env ENV", "Set environment") do |e|
options[:env] = e
end
opts.on("-t", "--type [TYPE]", [:dayly, :weekly, :monthly], "Type: dayly, weekly, monthly") do |t|
options[:type] = t
end
opts.on("-v", "--verbose", "Verbose") do |v|
options[:verbose] = v
end
end
opt_parser.parse!
################################################################################
cfg_file = YAML::load( File.open( "config/database.yml" ) )[options[:env]]
if cfg_file.nil?
pp "*** Error, config file is invalid"
return false
end
## Options for DB Dump (Only PostgreSql at moment)
db_opts = {}
db_opts[:host] = cfg_file['host'] || 'localhost'
db_opts[:adapter] = cfg_file['adapter']
db_opts[:database] = cfg_file['database']
db_opts[:user] = cfg_file['username']
db_opts[:password] = cfg_file['password']
################################################################################
pp "*** Options: #{options}" if options[:verbose]
def folder
"#{BAK_DIR}/#{db_opts[:database]}/#{options[:type]}"
end
pp "*** Folder: #{folder}" if options[:verbose]
if options[:dump]
system( "mkdir -p #{folder}" )
pp "*** Dumping DB" if options[:verbose]
ENV['PGPASSWORD'] = db_opts[:password]
system( "pg_dump -h #{db_opts[:host]} -U #{db_opts[:user]} #{db_opts[:database]} | bzip2 > #{folder}/#{TIMESTAMP}.sql.bz2" )
end
if options[:cleanup] > 0
system("find #{folder} -type f -prune -mtime +#{options[:cleanup]} -exec rm -f {} \;")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment