Class: S3

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

Instance Method Summary collapse

Constructor Details

#initialize(bucket, main_key) ⇒ S3

Returns a new instance of S3.



4
5
6
7
8
# File 'lib/biosphere/s3.rb', line 4

def initialize(bucket, main_key)
    @client = Aws::S3::Client.new
    @bucket_name = bucket
    @main_key = main_key
end

Instance Method Details

#release_lockObject



71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/biosphere/s3.rb', line 71

def release_lock()
    begin
        @client.delete_object({
            :bucket => @bucket_name,
            :key => "#{@main_key}/biosphere.lock"
        })
    rescue
        puts "\nCouldn't release the lock!"
        puts "Error: #{$!}"
        exit 1
    end
    puts "\nLock released successfully"
end

#retrieve(path_to_file) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/biosphere/s3.rb', line 29

def retrieve(path_to_file)
    filename = path_to_file.split('/')[-1]
    key = "#{@main_key}/#{filename}"
    puts "Fetching #{filename} from S3 from #{key}"
    begin
        resp = @client.get_object({
            :bucket => @bucket_name,
            :key => key
        })
        File.open(path_to_file, 'w') do |f|
            f.puts(resp.body.read)
        end
    rescue Aws::S3::Errors::NoSuchKey
        puts "Couldn't find remote file #{filename} from S3 at #{key}"
    rescue
        puts "\nError occurred while fetching the remote state, can't continue."
        puts "Error: #{$!}"
        exit 1
    end
end

#save(path_to_file) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/biosphere/s3.rb', line 10

def save(path_to_file)
    filename = path_to_file.split('/')[-1]
    key = "#{@main_key}/#{filename}"
    puts "Saving #{path_to_file} to S3 #{key}"
    begin
        File.open(path_to_file, 'rb') do |file|
            @client.put_object({
                :bucket => @bucket_name,
                :key => key,
                :body => file
            })
        end
    rescue
        puts "\nError occurred while saving the remote state, can't continue"
        puts "Error: #{$!}"
        exit 1
    end
end

#set_lockObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/biosphere/s3.rb', line 50

def set_lock()
    begin
        resp = @client.get_object({
            :bucket => @bucket_name,
            :key => "#{@main_key}/biosphere.lock"
        })
        puts "\nThe remote state is locked since #{resp.last_modified}\nCan't continue."
        exit 1
    rescue Aws::S3::Errors::NoSuchKey
        puts "\nRemote state was not locked, adding the lockfile.\n"
        @client.put_object({
            :bucket => @bucket_name,
            :key => "#{@main_key}/biosphere.lock"
        })
    rescue
        puts "\There was an error while accessing the lock. Can't continue.'"
        puts "Error: #{$!}"
        exit 1
    end
end