Class: S3Backup::Storage::S3

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeS3

Returns a new instance of S3.



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/s3_backup/storage/s3.rb', line 11

def initialize
  @connection = Aws::S3::Client.new(
    credentials: Aws::Credentials.new(
      Config.aws_access_key_id,
      Config.aws_secret_access_key
    ),
    region:              Config.aws_region,
    endpoint:            Config.aws_endpoint,
    stub_responses:      Config.aws_stub_responses
  )
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



9
10
11
# File 'lib/s3_backup/storage/s3.rb', line 9

def connection
  @connection
end

Instance Method Details

#clean!(base_name, bucket_path) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/s3_backup/storage/s3.rb', line 58

def clean!(base_name, bucket_path)
  prefix = File.join(bucket_path, base_name)

  s3_files = @connection.list_objects(bucket: Config.bucket, prefix: prefix).contents.sort_by(&:last_modified).reverse
  files_to_remove = s3_files[(Config.s3_keep || 1)..-1]

  return true if files_to_remove.nil? || files_to_remove.empty?

  @connection.delete_objects(
    bucket: Config.bucket,
    delete: {
      objects: files_to_remove.map {|f| {key: f.key} }
    }
  )

  true
end

#download!(database_name, bucket_path, file_path) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/s3_backup/storage/s3.rb', line 36

def download!(database_name, bucket_path, file_path)
  prefix = File.join(bucket_path, database_name)
  s3_backup_file = @connection.list_objects(bucket: Config.bucket, prefix: prefix).contents.sort_by(&:last_modified).reverse.first

  raise "#{database_name} file not found on s3" unless s3_backup_file

  file = File.open(file_path, 'wb')
  puts "File size: #{(s3_backup_file.size.to_f / 1024 / 1024).round(4)}MB, writing to #{file_path}"
  total_bytes = s3_backup_file.size
  remaining_bytes = s3_backup_file.size
  progress_bar
  
  @connection.get_object(bucket: Config.bucket, key: s3_backup_file.key) do |chunk|
    update_progress_bar(total_bytes, remaining_bytes)
    file.write chunk
    remaining_bytes -= chunk.size
  end
  file.close

  true
end

#upload!(file_name, bucket_path, file_path) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/s3_backup/storage/s3.rb', line 23

def upload!(file_name, bucket_path, file_path)
  upload_options = {
    bucket: Config.bucket,
    key: File.join(bucket_path, file_name),
    body: File.open(file_path)
  }

  upload_options[:server_side_encryption] = Config.aws_server_side_encryption if Config.aws_server_side_encryption
  @connection.put_object(upload_options)
  
  true
end