Class: DatabaseBackup

Inherits:
Object
  • Object
show all
Defined in:
lib/util/database_backup.rb

Constant Summary collapse

TMP_BACKUP_FILE =
"/tmp/mysql-backup-#{Time.now.to_i}"
BACKUP_BUCKET =
"#{ENV['ACCOUNT_ID']}-rwec2-mysql-backups"

Class Method Summary collapse

Class Method Details

.backup!Object


16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/util/database_backup.rb', line 16

def backup!
  unencrypted_contents = `mysqldump --all-databases`
  key = EzCrypto::Key.with_password ENV['SECRET_ACCESS_KEY'], 'saltoftheearth'
  encrypted_contents = key.encrypt unencrypted_contents
  File.open(TMP_BACKUP_FILE, 'w') { |f| f << encrypted_contents}
  begin
    AWS::S3::Bucket.find BACKUP_BUCKET
  rescue AWS::S3::NoSuchBucket
    AWS::S3::Bucket.create BACKUP_BUCKET
  end
  AWS::S3::S3Object.store(TMP_BACKUP_FILE, open(TMP_BACKUP_FILE), BACKUP_BUCKET)
ensure
  FileUtils.rm_f TMP_BACKUP_FILE if File.exists? TMP_BACKUP_FILE
end

.restore!(version) ⇒ Object


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/util/database_backup.rb', line 31

def restore!(version)
  begin
    all_objects = AWS::S3::Bucket.objects(BACKUP_BUCKET)
    latest = if version
      all_objects.detect { |o| o.key =~ /^.*(#{latest}).*$/ }
    else
      all_objects.sort_by { |o| Date.parse(o.about[:last_modified]) }.last
    end
    if latest
      encrypted_contents = latest.value
      key = EzCrypto::Key.with_password ENV['SECRET_ACCESS_KEY'], 'saltoftheearth'
      unencrypted_contents = key.decrypt encrypted_contents
      File.open(TMP_BACKUP_FILE, 'w') { |f| f << unencrypted_contents }
      %x(mysql < #{TMP_BACKUP_FILE})
    end
  rescue AWS::S3::NoSuchBucket
    STDERR.puts "Nothing to restore"
  ensure
    FileUtils.rm_f TMP_BACKUP_FILE if File.exists? TMP_BACKUP_FILE
  end
end