Skip to content

Instantly share code, notes, and snippets.

@stp-che
Last active October 2, 2015 19:58
Show Gist options
  • Save stp-che/2310085 to your computer and use it in GitHub Desktop.
Save stp-che/2310085 to your computer and use it in GitHub Desktop.
Simple backup automation
#!/bin/sh
d=`date +%Y%m%d`
path=/home/keeper/backup
pg_dump -U postgres -d my_database -n my_schema -f $path"dump"$d -O
zip -jq $path"dump"$d".zip" $path"dump"$d
C:\cygwin\bin\sh.exe -l -c 'cd /path/to/loding/script/folder && ruby load_backup.rb'
require 'rubygems'
require 'fileutils'
require 'pony'
BACKUP_DIR = "/path/to/backup"
REPORT_DIR = "#{File.expand_path File.dirname(__FILE__)}/synch_reports/#{Time.now.strftime('%Y-%m-%d')}"
REMOTE_SERVER = 'myserver'
REMOTE_USER = 'user'
REPORT_RECIPIENTS = '*******'
FileUtils.mkdir_p REPORT_DIR unless File.directory?(REPORT_DIR)
PARTS_TO_SYNCH = {
db: {remote: '/path/to/db/dumps', local: "#{BACKUP_DIR}/db"},
file_storage: {remote: '/path/to/file/storage', local: "#{BACKUP_DIR}/file_storage"}
}
PARTS_TO_SYNCH.each do |id, opts|
file_out = "#{REPORT_DIR}/#{id}.log"
file_err = "#{REPORT_DIR}/#{id}_err.log"
command = "rsync -avzu #{REMOTE_USER}@#{REMOTE_SERVER}:#{opts[:remote]} #{opts[:local]}"
puts command
Process.wait spawn(command, out: file_out, err: file_err)
end
errors = false
attachments = {}.tap do |h|
Dir["#{REPORT_DIR}/*"].select{|f| File.file?(f) && File.size(f) > 0}.each do |f|
errors = true if f =~ /_err/
h[File.basename(f)] = File.read f
end
end
Pony.mail({
to: REPORT_RECIPIENTS,
from: '*******',
subject: "backup report - #{errors ? 'WITH ERRORS' : 'OK'}",
body: "backup report - #{errors ? 'WITH ERRORS' : 'OK'}",
attachments: attachments,
via: :smtp,
via_options: {
address: '****',
port: '25',
user_name: '******',
password: '******',
authentication: :plain,
domain: "******"
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment