Class: BackupMongoS3::Storage

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

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Storage

Returns a new instance of Storage.



4
5
6
7
# File 'lib/backup_mongo_s3/storage.rb', line 4

def initialize(options)
  @s3     = AWS::S3.new({access_key_id: options[:access_key_id], secret_access_key: options[:secret_access_key]})
  @bucket = get_bucket(options[:bucket])
end

Instance Method Details

#delete_old_backups(prefix, history_days) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/backup_mongo_s3/storage.rb', line 86

def delete_old_backups(prefix, history_days)

  old_backups = []

  backups_time_limit = Time.now.utc.midnight - history_days.days

  backups = get_backups_list(prefix)

  backups.each do |backup|
    if backup.last_modified.utc < backups_time_limit
      old_backups << backup
    end
  end

  @bucket.objects.delete(old_backups) unless old_backups.empty?

end

#download(storage_path, storage_file_name, file_name) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/backup_mongo_s3/storage.rb', line 45

def download(storage_path, storage_file_name, file_name)
  key = File.join(storage_path, storage_file_name + '.backup')

  begin

    file = File.open(file_name, 'wb')

    obj = @bucket.objects[key]

    response = obj.read do |chunk|
      file.write(chunk)
    end

    file.close

    checksum = get_signature(file_name)

    if checksum != response[:meta]['checksum']
      raise 'Backup signature is not valid'
    end

  rescue Exception => error
    raise "Error download file <#{key}> from s3 to <#{file_name}>: #{error.message}"
  end

end

#get_backups_list(prefix = '', limit = 100) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
# File 'lib/backup_mongo_s3/storage.rb', line 73

def get_backups_list(prefix = '', limit = 100)
  result =[]

  @bucket.objects.with_prefix(prefix).each(:limit => limit) do |object|
    if File.extname(object.key) == '.backup'
      result << object
    end
  end

  result
end

#upload(storage_path, file_name) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/backup_mongo_s3/storage.rb', line 21

def upload(storage_path, file_name)
  key = File.join(storage_path, Time.now.utc.strftime('%Y%m%d') + '.backup')

  checksum = get_signature(file_name)

  begin

    file = File.open(file_name, 'rb')

    obj = @bucket.objects[key]

    obj.write(:content_length => file.size, metadata: {checksum: checksum}) do |buffer, bytes|
      buffer.write(file.read(bytes))
    end

    file.close

  rescue Exception => error
    raise "Error upload file <#{file_name}> to s3 <#{key}>: #{error.message}"
  end

end