Skip to content

Instantly share code, notes, and snippets.

@link82 link82/backup.rb
Created Aug 27, 2013

Embed
What would you like to do?
require 'rubygems'
require 'active_record'
require 'yaml'
require 'logger'
require 'fileutils'
require 'aws/s3'
ROOT = File.expand_path(File.dirname(__FILE__))
CONFIG = YAML.load_file(File.join(ROOT, "config", "database.yml"))
TMP_BACKUP = File.join(ROOT, "tmp", "backup")
CLONE_STRING = "git clone git@YOUR-DOMAIN.com:"
BACKUP_FILENAME = "REPOS.BACKUP-#{Time.now.strftime("%Y.%m.%d-%H.%M.%S")}.tar.gz"
LOG = Logger.new(File.join(ROOT, "log", "backup.log"))
begin
ActiveRecord::Base.establish_connection(
:adapter => CONFIG['production']['adapter'],
:host => "localhost",
:username => CONFIG['production']['username'],
:password => CONFIG['production']['password'],
:database => CONFIG['production']['database']
)
rescue => e
LOG.error "Error with active record adapter"
end
#CREATE MODEL FOR PROJECTS
class Project < ActiveRecord::Base
end
#DELETE EXISTING FOLDER AND RECREATE TO START FRESH
LOG.info "Clearing old backup files"
FileUtils.rm_rf TMP_BACKUP if File.directory?(TMP_BACKUP)
FileUtils.mkdir_p TMP_BACKUP
#ITERATE THROUGH ALL THE PROJECT RECORDS
Project.all.each do |p|
LOG.info "Cloning #{p.code} repo"
`#{CLONE_STRING}#{p.code} #{File.join(TMP_BACKUP, p.code)}`
end
begin
#compress the newly created backup
LOG.info "Compressing #{BACKUP_FILENAME}"
FileUtils.mkdir_p File.join(ROOT, "backups")#create dir if not exists
`tar -zcPf #{File.join(ROOT, "backups", BACKUP_FILENAME)} #{TMP_BACKUP} >> #{File.join(ROOT, "log", "backup.log")}`
FileUtils.rm_rf TMP_BACKUP if File.directory?(TMP_BACKUP)
rescue => e
LOG.error "Error compressing archive"
end
begin
#connect to amazon s3
LOG.info "Connecting to amazon s3"
AWS::S3::Base.establish_connection!(:access_key_id => 'ACCESS_KEY_GOES_HERE', :secret_access_key => 'SECRET_KEY_GOES_HERE')
LOG.info "AWS Connection established"
LOG.info "Uploading to amazon bucket"
AWS::S3::S3Object.store(BACKUP_FILENAME, File.open(File.join(ROOT, "backups", BACKUP_FILENAME)), 'BUCKET_NAME_GOES_HERE')
LOG.info "Finished uploading to amazon bucket"
rescue => e
LOG.error "ERROR uploading to amazon bucket"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.