Class: DB2S3

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

Defined Under Namespace

Classes: Config, S3Store

Instance Method Summary collapse

Constructor Details

#initializeDB2S3

Returns a new instance of DB2S3.



13
14
# File 'lib/db2s3.rb', line 13

def initialize
end

Instance Method Details

#cleanObject

TODO: This method really needs specs



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/db2s3.rb', line 29

def clean
  to_keep = []
  filelist = store.list
  files = filelist.reject {|file| file.ends_with?(most_recent_dump_file_name) }.collect do |file|
    {
      :path => file,
      :date => Time.parse(file.split('-').last.split('.').first)
    }
  end
  # Keep all backups from the past day
  files.select {|x| x[:date] >= 1.day.ago }.each do |backup_for_day|
    to_keep << backup_for_day
  end

  # Keep one backup per day from the last week
  files.select {|x| x[:date] >= 1.week.ago }.group_by {|x| x[:date].strftime("%Y%m%d") }.values.each do |backups_for_last_week|
    to_keep << backups_for_last_week.sort_by{|x| x[:date].strftime("%Y%m%d") }.first
  end

  # Keep one backup per week since forever
  files.group_by {|x| x[:date].strftime("%Y%W") }.values.each do |backups_for_week|
    to_keep << backups_for_week.sort_by{|x| x[:date].strftime("%Y%m%d") }.first
  end

  to_destroy = filelist - to_keep.uniq.collect {|x| x[:path] }
  to_destroy.delete_if {|x| x.ends_with?(most_recent_dump_file_name) }
  to_destroy.each do |file|
    store.delete(file.split('/').last)
  end
end

#full_backupObject



16
17
18
19
20
# File 'lib/db2s3.rb', line 16

def full_backup
  file_name = "dump-#{db_credentials[:database]}-#{Time.now.utc.strftime("%Y%m%d%H%M")}.sql.gz"
  store.store(file_name, open(dump_db.path))
  store.store(most_recent_dump_file_name, file_name)
end

#restoreObject



22
23
24
25
26
# File 'lib/db2s3.rb', line 22

def restore
  dump_file_name = store.fetch(most_recent_dump_file_name).read
  file = store.fetch(dump_file_name)
  run "gunzip -c #{file.path} | mysql #{mysql_options}"
end

#statisticsObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/db2s3.rb', line 60

def statistics
    # From http://mysqlpreacher.com/wordpress/tag/table-size/
  results = ActiveRecord::Base.connection.execute(<<-EOS)
  SELECT
    engine,
    ROUND(data_length/1024/1024,2) total_size_mb,
    ROUND(index_length/1024/1024,2) total_index_size_mb,
    table_rows,
    table_name article_attachment
    FROM information_schema.tables
    WHERE table_schema = '#{db_credentials[:database]}'
    ORDER BY total_size_mb + total_index_size_mb desc;
  EOS
  rows = []
  results.each {|x| rows << x.to_a }
  rows
end