Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 95 lines (80 sloc) 2.33 KB
#!/usr/bin/env ruby
# Add the following to $HOME/.ssh/authorized_keys on backed up hosts
# (replacing PUBLICKEY with contents of $HOME/.ssh/backup.pub):
#
# command="rsync --server --sender -vlogDtpr . /var/local/" PUBLICKEY...
require 'rubygems'
require 'aws/s3'
class Backup
@@backupdir = File.join(ENV['HOME'], 'backups')
@@hosts = %w( moa taiko kotuku hoiho )
def initialize(bucket_name = nil)
@bucket_name = bucket_name || 'backup.urgetopunt.com'
connect
end
def run(*hosts)
queue = hosts.empty? ? @@hosts : @@hosts & hosts
queue.each { |host| run_host(host) }
end
def bucket
@bucket ||= AWS::S3::Bucket.find(@bucket_name)
end
def objects(reload = nil)
@objects ||= bucket.objects(reload)
end
private
def run_host(host)
dir = File.join(@@backupdir, host)
open(File.join(dir, '.status'), 'w') do |log|
log.puts "Started #{Time.now}"
puts "[ run #{host} ]"
pull host, dir
push host, dir
purge host
log.puts "Finished #{Time.now}"
end
end
def pull(host, dir)
FileUtils.mkdir_p(dir)
%x{ rsync -av -e "ssh -i #{ENV['HOME']}/.ssh/backup" --delete --exclude=.status #{host}:/var/local/ #{dir} }
end
def push(host, dir)
Dir["#{dir}/*"].each do |file|
key = file.sub(%r{^#{@@backupdir}/}, '')
obj = objects.detect {|o| o.key == key}
if obj.nil? || Time.parse(obj.about['last-modified']) < File.mtime(file)
puts "+upload #{key}"
AWS::S3::S3Object.store key, open(file), @bucket_name
end
end
end
def purge(host)
objects.select {|o| o.key =~ %r{^#{host}/}}.each do |obj|
unless File.exist? File.join(@@backupdir, obj.key)
puts "-purge #{obj.key}"
obj.delete
end
end
end
def connect
get_credentials
AWS::S3::Base.establish_connection!(
:access_key_id => @access_key,
:secret_access_key => @secret_access_key
)
end
def get_credentials
File.open(File.join(ENV['HOME'], '.amazon_keys')) do |f|
until f.eof? do
case f.readline
when /^AMAZON_ACCESS_KEY_ID=['"]?([A-Z0-9]+)['"]?/ then @access_key = $1
when /^AMAZON_SECRET_ACCESS_KEY=['"]?([A-Za-z0-9]+)['"]?/ then @secret_access_key = $1
end
end
end
end
end
if __FILE__ == $0
backup = Backup.new
backup.run(*ARGV)
end