Class: OpenC3::AwsBucket
- Defined in:
- lib/openc3/utilities/aws_bucket.rb
Direct Known Subclasses
Constant Summary collapse
- CREATE_CHECK_COUNT =
10 seconds
100
Instance Method Summary collapse
- #check_object(bucket:, key:, retries: true) ⇒ Object
- #create(bucket) ⇒ Object
- #delete(bucket) ⇒ Object
- #delete_object(bucket:, key:) ⇒ Object
- #delete_objects(bucket:, keys:) ⇒ Object
- #ensure_public(bucket) ⇒ Object
-
#ensure_scriptrunner_policy(config_bucket, logs_bucket) ⇒ Object
Apply bucket policy to grant ScriptRunner user access to config and logs buckets This provides reduced permissions compared to the root user for security.
- #exist?(bucket) ⇒ Boolean
- #get_object(bucket:, key:, path: nil, range: nil) ⇒ Object
-
#head_object(bucket:, key:) ⇒ Object
get metadata for a specific object.
-
#initialize ⇒ AwsBucket
constructor
A new instance of AwsBucket.
-
#list_files(bucket:, path:, only_directories: false, metadata: false) ⇒ Object
Lists the files under a specified path.
- #list_objects(bucket:, prefix: nil, max_request: 1000, max_total: 100_000) ⇒ Object
- #presigned_request(bucket:, key:, method:, internal: true) ⇒ Object
-
#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.
Methods inherited from Bucket
Constructor Details
#initialize ⇒ AwsBucket
Returns a new instance of AwsBucket.
23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 23 def initialize super() @client = Aws::S3::Client.new @aws_arn = ENV['OPENC3_AWS_ARN_PREFIX'] || 'arn:aws' # Checksums are supported by real AWS S3 but may not be supported by # S3-compatible backends like versitygw. Auto-detect based on # whether a custom endpoint is configured. Can be overridden with ENV var. @use_checksum = if ENV.key?('OPENC3_NO_S3_CHECKSUM') ENV['OPENC3_NO_S3_CHECKSUM'].to_s.empty? # Empty string means use checksum else ENV.fetch('OPENC3_CLOUD', 'local').downcase == 'aws' end end |
Instance Method Details
#check_object(bucket:, key:, retries: true) ⇒ Object
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 314 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
37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 37 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
201 202 203 204 205 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 201 def delete(bucket) if exist?(bucket) @client.delete_bucket({ bucket: bucket }) end end |
#delete_object(bucket:, key:) ⇒ Object
334 335 336 337 338 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 334 def delete_object(bucket:, key:) @client.delete_object(bucket: bucket, key: key) rescue Exception => e Logger.error("Error deleting object bucket: #{bucket}, key: #{key}: #{e.}") end |
#delete_objects(bucket:, keys:) ⇒ Object
340 341 342 343 344 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 340 def delete_objects(bucket:, keys:) @client.delete_objects(bucket: bucket, delete: { objects: keys.map {|key| { key: key } } }) rescue Exception => e Logger.error("Error deleting objects bucket: #{bucket}, keys: #{keys}: #{e.}") end |
#ensure_public(bucket) ⇒ Object
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 89 90 91 92 93 94 95 96 97 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 49 def ensure_public(bucket) unless ENV.fetch('OPENC3_NO_BUCKET_POLICY', false) 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 begin = { bucket: bucket, policy: policy } [:checksum_algorithm] = "SHA256" if @use_checksum @client.put_bucket_policy() rescue Aws::S3::Errors::NotImplemented, Aws::S3::Errors::ServiceError, Aws::S3::Errors::InternalError => e Logger.warn("put_bucket_policy not supported by S3 backend: #{e.}") end end end |
#ensure_scriptrunner_policy(config_bucket, logs_bucket) ⇒ Object
Apply bucket policy to grant ScriptRunner user access to config and logs buckets This provides reduced permissions compared to the root user for security
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 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 184 185 186 187 188 189 190 191 192 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 101 def ensure_scriptrunner_policy(config_bucket, logs_bucket) sr_username = ENV['OPENC3_SR_BUCKET_USERNAME'] return unless sr_username return if sr_username == ENV['OPENC3_BUCKET_USERNAME'] # Same as root, no policy needed # Policy for config bucket - read targets, read/write targets_modified # Note: versitygw expects Principal as comma-separated raw usernames config_policy = <<~EOL { "Version": "2012-10-17", "Statement": [ { "Sid": "ScriptRunnerListBucket", "Effect": "Allow", "Principal": ["#{sr_username}"], "Action": [ "s3:ListBucket", "s3:GetBucketLocation" ], "Resource": "#{@aws_arn}:s3:::#{config_bucket}" }, { "Sid": "ScriptRunnerReadTargets", "Effect": "Allow", "Principal": ["#{sr_username}"], "Action": "s3:GetObject", "Resource": "#{@aws_arn}:s3:::#{config_bucket}/*" }, { "Sid": "ScriptRunnerWriteTargetsModified", "Effect": "Allow", "Principal": ["#{sr_username}"], "Action": [ "s3:PutObject", "s3:DeleteObject" ], "Resource": "#{@aws_arn}:s3:::#{config_bucket}/*/targets_modified/*" } ] } EOL # Policy for logs bucket - read/write tool_logs/sr logs_policy = <<~EOL { "Version": "2012-10-17", "Statement": [ { "Sid": "ScriptRunnerListBucket", "Effect": "Allow", "Principal": ["#{sr_username}"], "Action": [ "s3:ListBucket", "s3:GetBucketLocation" ], "Resource": "#{@aws_arn}:s3:::#{logs_bucket}" }, { "Sid": "ScriptRunnerWriteToolLogs", "Effect": "Allow", "Principal": ["#{sr_username}"], "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject" ], "Resource": "#{@aws_arn}:s3:::#{logs_bucket}/*/tool_logs/sr/*" } ] } EOL begin Logger.info("Applying ScriptRunner bucket policy to #{config_bucket}") = { bucket: config_bucket, policy: config_policy } [:checksum_algorithm] = "SHA256" if @use_checksum @client.put_bucket_policy() rescue Aws::S3::Errors::NotImplemented, Aws::S3::Errors::ServiceError, Aws::S3::Errors::InternalError => e Logger.warn("put_bucket_policy for #{config_bucket} not supported by S3 backend: #{e.}") Logger.warn("Policy applied:\n#{config_policy}") end begin Logger.info("Applying ScriptRunner bucket policy to #{logs_bucket}") = { bucket: logs_bucket, policy: logs_policy } [:checksum_algorithm] = "SHA256" if @use_checksum @client.put_bucket_policy() rescue Aws::S3::Errors::NotImplemented, Aws::S3::Errors::ServiceError, Aws::S3::Errors::InternalError => e Logger.warn("put_bucket_policy for #{logs_bucket} not supported by S3 backend: #{e.}") Logger.warn("Policy applied:\n#{logs_policy}") end end |
#exist?(bucket) ⇒ Boolean
194 195 196 197 198 199 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 194 def exist?(bucket) @client.head_bucket({ bucket: bucket }) true rescue Aws::S3::Errors::NotFound false end |
#get_object(bucket:, key:, path: nil, range: nil) ⇒ Object
207 208 209 210 211 212 213 214 215 216 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 207 def get_object(bucket:, key:, path: nil, range: nil) if path @client.get_object(bucket: bucket, key: key, response_target: path, range: range) else @client.get_object(bucket: bucket, key: key, range: range) 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
290 291 292 293 294 295 296 297 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 290 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
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 240 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
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 218 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
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 346 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
300 301 302 303 304 305 306 307 308 309 310 311 |
# File 'lib/openc3/utilities/aws_bucket.rb', line 300 def put_object(bucket:, key:, body:, content_type: nil, cache_control: nil, metadata: nil) = { bucket: bucket, key: key, body: body, content_type: content_type, cache_control: cache_control, metadata: } [:checksum_algorithm] = "SHA256" if @use_checksum @client.put_object(**) end |