Class: ServerBackups::S3

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

Constant Summary collapse

PROVIDER =
'AWS'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ S3

Returns a new instance of S3.



9
10
11
12
# File 'lib/server_backups/s3.rb', line 9

def initialize(config)
    @config = config
    @logger = config.logger
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



8
9
10
# File 'lib/server_backups/s3.rb', line 8

def config
  @config
end

#loggerObject (readonly)

Returns the value of attribute logger.



8
9
10
# File 'lib/server_backups/s3.rb', line 8

def logger
  @logger
end

Instance Method Details

#bucketObject



23
24
25
# File 'lib/server_backups/s3.rb', line 23

def bucket
    @bucket ||= Aws::S3::Bucket.new(config.bucket, client: client)
end

#clientObject



14
15
16
17
18
19
20
21
# File 'lib/server_backups/s3.rb', line 14

def client
    @client ||= begin
        Aws.config[:credentials] = Aws::Credentials.new(
            config.access_key_id, config.secret_access_key
        )
        Aws::S3::Client.new region: config.region
    end
end

#delete_files_not_newer_than(key, age) ⇒ Object



31
32
33
34
35
# File 'lib/server_backups/s3.rb', line 31

def delete_files_not_newer_than(key, age)
    bucket.objects(prefix: key).each do |file|
        destroy key, true unless file.last_modified.to_datetime > age
    end
end

#destroy(key, existence_known = false) ⇒ Object



43
44
45
46
# File 'lib/server_backups/s3.rb', line 43

def destroy(key, existence_known = false)
    return unless existence_known || exists?(key)
    client.delete_object bucket: config.bucket, key: key
end

#exists?(path) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
# File 'lib/server_backups/s3.rb', line 37

def exists?(path)
    logger.debug "Exists? #{config.bucket}  #{path}"
    !bucket.objects(prefix: path).to_a.empty?
    # !!client.head_object(bucket: config.bucket, key: path)
end

#get_ordered_collection(prefix) ⇒ Object



27
28
29
# File 'lib/server_backups/s3.rb', line 27

def get_ordered_collection(prefix)
    OrderedBackupFileCollection.new bucket.objects(prefix: prefix)
end

#save(local_file_name, s3_key) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/server_backups/s3.rb', line 48

def save(local_file_name, s3_key)
    full_path = if s3_key[-1] == '/'
                    File.join(s3_key, File.basename(local_file_name))
                else
                    s3_key
                end

    return if exists?(full_path)
    file = Aws::S3::Object.new(config.bucket, full_path, client: client)
    file.put(
        acl: 'private',
        body: File.open(local_file_name, 'rb'),
        content_md5: md5of(local_file_name),
        storage_class: 'STANDARD_IA'
    )
end