Class: OpenC3::AwsBucket

Inherits:
Bucket show all
Defined in:
lib/openc3/utilities/aws_bucket.rb

Direct Known Subclasses

LocalBucket

Constant Summary collapse

CREATE_CHECK_COUNT =

10 seconds

100

Instance Method Summary collapse

Methods inherited from Bucket

getClient

Constructor Details

#initializeAwsBucket

Returns a new instance of AwsBucket.



28
29
30
31
32
# File 'lib/openc3/utilities/aws_bucket.rb', line 28

def initialize
  super()
  @client = Aws::S3::Client.new
  @aws_arn = ENV['OPENC3_AWS_ARN_PREFIX'] || 'arn:aws'
end

Instance Method Details

#check_object(bucket:, key:, retries: true) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/openc3/utilities/aws_bucket.rb', line 203

def check_object(bucket:, key:, retries: true)
  if retries
    @client.wait_until(:object_exists,
      {
        bucket: bucket,
        key: key
      },
      {
        max_attempts: 30,
        delay: 0.1, # seconds
      }
    )
    true
  else
    head_object(bucket: bucket, key: key)
  end
rescue NotFound, Aws::Waiters::Errors::TooManyAttemptsError
  false
end

#create(bucket) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/openc3/utilities/aws_bucket.rb', line 34

def create(bucket)
  unless exist?(bucket)
    @client.create_bucket({ bucket: bucket })
    count = 0
    until exist?(bucket) or count > CREATE_CHECK_COUNT
      sleep(0.1)
      count += 1
    end
  end
  bucket
end

#delete(bucket) ⇒ Object



97
98
99
100
101
# File 'lib/openc3/utilities/aws_bucket.rb', line 97

def delete(bucket)
  if exist?(bucket)
    @client.delete_bucket({ bucket: bucket })
  end
end

#delete_object(bucket:, key:) ⇒ Object



223
224
225
226
227
# File 'lib/openc3/utilities/aws_bucket.rb', line 223

def delete_object(bucket:, key:)
  @client.delete_object(bucket: bucket, key: key)
rescue Exception
  Logger.error("Error deleting object bucket: #{bucket}, key: #{key}")
end

#delete_objects(bucket:, keys:) ⇒ Object



229
230
231
232
233
# File 'lib/openc3/utilities/aws_bucket.rb', line 229

def delete_objects(bucket:, keys:)
  @client.delete_objects(bucket: bucket, delete: { objects: keys.map {|key| { key: key } } })
rescue Exception
  Logger.error("Error deleting objects bucket: #{bucket}, keys: #{keys}")
end

#ensure_public(bucket) ⇒ Object



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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/openc3/utilities/aws_bucket.rb', line 46

def ensure_public(bucket)
  unless ENV['OPENC3_NO_BUCKET_POLICY']
    policy = <<~EOL
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Action": [
            "s3:GetBucketLocation",
            "s3:ListBucket"
          ],
          "Effect": "Allow",
          "Principal": {
            "AWS": [
              "*"
            ]
          },
          "Resource": [
            "#{@aws_arn}:s3:::#{bucket}"
          ],
          "Sid": ""
        },
        {
          "Action": [
            "s3:GetObject"
          ],
          "Effect": "Allow",
          "Principal": {
            "AWS": [
              "*"
            ]
          },
          "Resource": [
            "#{@aws_arn}:s3:::#{bucket}/*"
          ],
          "Sid": ""
        }
      ]
    }
    EOL
    @client.put_bucket_policy({ bucket: bucket, policy: policy, checksum_algorithm: "SHA256" })
  end
end

#exist?(bucket) ⇒ Boolean

Returns:

  • (Boolean)


90
91
92
93
94
95
# File 'lib/openc3/utilities/aws_bucket.rb', line 90

def exist?(bucket)
  @client.head_bucket({ bucket: bucket })
  true
rescue Aws::S3::Errors::NotFound
  false
end

#get_object(bucket:, key:, path: nil) ⇒ Object



103
104
105
106
107
108
109
110
111
112
# File 'lib/openc3/utilities/aws_bucket.rb', line 103

def get_object(bucket:, key:, path: nil)
  if path
    @client.get_object(bucket: bucket, key: key, response_target: path)
  else
    @client.get_object(bucket: bucket, key: key)
  end
# If the key is not found return nil
rescue Aws::S3::Errors::NoSuchKey
  nil
end

#head_object(bucket:, key:) ⇒ Object

get metadata for a specific object



186
187
188
189
190
191
192
193
# File 'lib/openc3/utilities/aws_bucket.rb', line 186

def head_object(bucket:, key:)
  @client.head_object({
    bucket: bucket,
    key: key
  })
rescue Aws::S3::Errors::NotFound
  raise NotFound, "Object '#{bucket}/#{key}' does not exist."
end

#list_files(bucket:, path:, only_directories: false, metadata: false) ⇒ Object

Lists the files under a specified path



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/openc3/utilities/aws_bucket.rb', line 136

def list_files(bucket:, path:, only_directories: false, metadata: false)
  # Trailing slash is important in AWS S3 when listing files
  # See https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/S3/Types/ListObjectsV2Output.html#common_prefixes-instance_method
  if path[-1] != '/'
    path += '/'
  end
  # If we're searching for the root then kill the path or AWS will return nothing
  path = nil if path == '/'

  token = nil
  result = []
  dirs = []
  files = []
  while true
    resp = @client.list_objects_v2({
      bucket: bucket,
      max_keys: 1000,
      prefix: path,
      delimiter: '/',
      continuation_token: token
    })
    resp.common_prefixes.each do |item|
      # If path was DEFAULT/targets_modified/ then the
      # results look like DEFAULT/targets_modified/INST/
      dirs << item.prefix.split('/')[-1]
    end
    if only_directories
      result = dirs
    else
      resp.contents.each do |aws_item|
        item = {}
        item['name'] = aws_item.key.split('/')[-1]
        item['modified'] = aws_item.last_modified
        item['size'] = aws_item.size
        if 
          item['metadata'] = head_object(bucket: bucket, key: aws_item.key)
        end
        files << item
      end
      result = [dirs, files]
    end
    break unless resp.is_truncated
    token = resp.next_continuation_token
  end
  result
rescue Aws::S3::Errors::NoSuchBucket
  raise NotFound, "Bucket '#{bucket}' does not exist."
end

#list_objects(bucket:, prefix: nil, max_request: 1000, max_total: 100_000) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/openc3/utilities/aws_bucket.rb', line 114

def list_objects(bucket:, prefix: nil, max_request: 1000, max_total: 100_000)
  token = nil
  result = []
  while true
    resp = @client.list_objects_v2({
      bucket: bucket,
      max_keys: max_request,
      prefix: prefix,
      continuation_token: token
    })
    result.concat(resp.contents)
    break if result.length >= max_total
    break unless resp.is_truncated
    token = resp.next_continuation_token
  end
  # Array of objects with key and size methods
  result
rescue Aws::S3::Errors::NoSuchBucket
  raise NotFound, "Bucket '#{bucket}' does not exist."
end

#presigned_request(bucket:, key:, method:, internal: true) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/openc3/utilities/aws_bucket.rb', line 235

def presigned_request(bucket:, key:, method:, internal: true)
  s3_presigner = Aws::S3::Presigner.new

  if internal
    prefix = '/'
  else
    prefix = '/files/'
  end

  url, headers = s3_presigner.presigned_request(method, bucket: bucket, key: key)
  return {
    :url => prefix + url.split('/')[3..-1].join('/'),
    :headers => headers,
    :method => method.to_s.split('_')[0],
  }
end

#put_object(bucket:, key:, body:, content_type: nil, cache_control: nil, metadata: nil) ⇒ Object

put_object fires off the request to store but does not confirm



196
197
198
199
200
# File 'lib/openc3/utilities/aws_bucket.rb', line 196

def put_object(bucket:, key:, body:, content_type: nil, cache_control: nil, metadata: nil)
  @client.put_object(bucket: bucket, key: key, body: body,
    content_type: content_type, cache_control: cache_control, metadata: ,
    checksum_algorithm: "SHA256")
end