-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy paths3_object.rb
1795 lines (1624 loc) · 63.8 KB
/
s3_object.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
89
90
91
92
93
94
95
96
97
98
99
100
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
require 'uri'
require 'base64'
module AWS
class S3
# Represents an object in S3. Objects live in a bucket and have
# unique keys.
#
# # Getting Objects
#
# You can get an object by its key.
#
# s3 = AWS::S3.new
# obj = s3.buckets['my-bucket'].objects['key'] # no request made
#
# You can also get objects by enumerating a objects in a bucket.
#
# bucket.objects.each do |obj|
# puts obj.key
# end
#
# See {ObjectCollection} for more information on finding objects.
#
# # Creating Objects
#
# You create an object by writing to it. The following two
# expressions are equivalent.
#
# obj = bucket.objects.create('key', 'data')
# obj = bucket.objects['key'].write('data')
#
# # Writing Objects
#
# To upload data to S3, you simply need to call {#write} on an object.
#
# obj.write('Hello World!')
# obj.read
# #=> 'Hello World!'
#
# ## Uploading Files
#
# You can upload a file to S3 in a variety of ways. Given a path
# to a file (as a string) you can do any of the following:
#
# # specify the data as a path to a file
# obj.write(Pathname.new(path_to_file))
#
# # also works this way
# obj.write(:file => path_to_file)
#
# # Also accepts an open file object
# file = File.open(path_to_file, 'rb')
# obj.write(file)
#
# All three examples above produce the same result. The file
# will be streamed to S3 in chunks. It will not be loaded
# entirely into memory.
#
# ## Streaming Uploads
#
# When you call {#write} with an IO-like object, it will be streamed
# to S3 in chunks.
#
# While it is possible to determine the size of many IO objects, you may
# have to specify the :content_length of your IO object.
# If the exact size can not be known, you may provide an
# `:estimated_content_length`. Depending on the size (actual or
# estimated) of your data, it will be uploaded in a single request or
# in multiple requests via {#multipart_upload}.
#
# You may also stream uploads to S3 using a block:
#
# obj.write do |buffer, bytes|
# # writing fewer than the requested number of bytes to the buffer
# # will cause write to stop yielding to the block
# end
#
# # Reading Objects
#
# You can read an object directly using {#read}. Be warned, this will
# load the entire object into memory and is not recommended for large
# objects.
#
# obj.write('abc')
# puts obj.read
# #=> abc
#
# ## Streaming Downloads
#
# If you want to stream an object from S3, you can pass a block
# to {#read}.
#
# File.open('output', 'wb') do |file|
# large_object.read do |chunk|
# file.write(chunk)
# end
# end
#
# # Encryption
#
# Amazon S3 can encrypt objects for you service-side. You can also
# use client-side encryption.
#
# ## Server Side Encryption
#
# You can specify to use server side encryption when writing an object.
#
# obj.write('data', :server_side_encryption => :aes256)
#
# You can also make this the default behavior.
#
# AWS.config(:s3_server_side_encryption => :aes256)
#
# s3 = AWS::S3.new
# s3.buckets['name'].objects['key'].write('abc') # will be encrypted
#
# ## Client Side Encryption
#
# Client side encryption utilizes envelope encryption, so that your keys are
# never sent to S3. You can use a symetric key or an asymmetric
# key pair.
#
# ### Symmetric Key Encryption
#
# An AES key is used for symmetric encryption. The key can be 128, 192,
# and 256 bit sizes. Start by generating key or read a previously
# generated key.
#
# # generate a new random key
# my_key = OpenSSL::Cipher.new("AES-256-ECB").random_key
#
# # read an existing key from disk
# my_key = File.read("my_key.der")
#
# Now you can encrypt locally and upload the encrypted data to S3.
# To do this, you need to provide your key.
#
# obj = bucket.objects["my-text-object"]
#
# # encrypt then upload data
# obj.write("MY TEXT", :encryption_key => my_key)
#
# # try read the object without decrypting, oops
# obj.read
# #=> '.....'
#
# Lastly, you can download and decrypt by providing the same key.
#
# obj.read(:encryption_key => my_key)
# #=> "MY TEXT"
#
# ### Asymmetric Key Pair
#
# A RSA key pair is used for asymmetric encryption. The public key is used
# for encryption and the private key is used for decryption. Start
# by generating a key.
#
# my_key = OpenSSL::PKey::RSA.new(1024)
#
# Provide your key to #write and the data will be encrypted before it
# is uploaded. Pass the same key to #read to decrypt the data
# when you download it.
#
# obj = bucket.objects["my-text-object"]
#
# # encrypt and upload the data
# obj.write("MY TEXT", :encryption_key => my_key)
#
# # download and decrypt the data
# obj.read(:encryption_key => my_key)
# #=> "MY TEXT"
#
# ### Configuring storage locations
#
# By default, encryption materials are stored in the object metadata.
# If you prefer, you can store the encryption materials in a separate
# object in S3. This object will have the same key + '.instruction'.
#
# # new object, does not exist yet
# obj = bucket.objects["my-text-object"]
#
# # no instruction file present
# bucket.objects['my-text-object.instruction'].exists?
# #=> false
#
# # store the encryption materials in the instruction file
# # instead of obj#metadata
# obj.write("MY TEXT",
# :encryption_key => MY_KEY,
# :encryption_materials_location => :instruction_file)
#
# bucket.objects['my-text-object.instruction'].exists?
# #=> true
#
# If you store the encryption materials in an instruction file, you
# must tell #read this or it will fail to find your encryption materials.
#
# # reading an encrypted file whos materials are stored in an
# # instruction file, and not metadata
# obj.read(:encryption_key => MY_KEY,
# :encryption_materials_location => :instruction_file)
#
# ### Configuring default behaviors
#
# You can configure the default key such that it will automatically
# encrypt and decrypt for you. You can do this globally or for a
# single S3 interface
#
# # all objects uploaded/downloaded with this s3 object will be
# # encrypted/decrypted
# s3 = AWS::S3.new(:s3_encryption_key => "MY_KEY")
#
# # set the key to always encrypt/decrypt
# AWS.config(:s3_encryption_key => "MY_KEY")
#
# You can also configure the default storage location for the encryption
# materials.
#
# AWS.config(:s3_encryption_materials_location => :instruction_file)
#
class S3Object
include Core::Model
include DataOptions
include ACLOptions
include AWS::S3::EncryptionUtils
# @param [Bucket] bucket The bucket this object belongs to.
# @param [String] key The object's key.
def initialize(bucket, key, opts = {})
@content_length = opts.delete(:content_length)
@etag = opts.delete(:etag)
@last_modified = opts.delete(:last_modified)
super
@key = key
@bucket = bucket
end
# @return [String] The objects unique key
attr_reader :key
# @return [Bucket] The bucket this object is in.
attr_reader :bucket
# @api private
def inspect
"<#{self.class}:#{bucket.name}/#{key}>"
end
# @return [Boolean] Returns true if the other object belongs to the
# same bucket and has the same key.
def == other
other.kind_of?(S3Object) and other.bucket == bucket and other.key == key
end
alias_method :eql?, :==
# @return [Boolean] Returns `true` if the object exists in S3.
def exists?
head
rescue Errors::NoSuchKey => e
false
else
true
end
# Performs a HEAD request against this object and returns an object
# with useful information about the object, including:
#
# * metadata (hash of user-supplied key-value pairs)
# * content_length (integer, number of bytes)
# * content_type (as sent to S3 when uploading the object)
# * etag (typically the object's MD5)
# * server_side_encryption (the algorithm used to encrypt the
# object on the server side, e.g. `:aes256`)
#
# @param [Hash] options
# @option options [String] :version_id Which version of this object
# to make a HEAD request against.
# @return A head object response with metadata,
# content_length, content_type, etag and server_side_encryption.
def head options = {}
client.head_object(options.merge(
:bucket_name => bucket.name, :key => key))
end
# Returns the object's ETag.
#
# Generally the ETAG is the MD5 of the object. If the object was
# uploaded using multipart upload then this is the MD5 all of the
# upload-part-md5s.
#
# @return [String] Returns the object's ETag
def etag
@etag = config.s3_cache_object_attributes && @etag || head[:etag]
end
# Returns the object's last modified time.
#
# @return [Time] Returns the object's last modified time.
def last_modified
@last_modified = config.s3_cache_object_attributes && @last_modified || head[:last_modified]
end
# @return [Integer] Size of the object in bytes.
def content_length
@content_length = config.s3_cache_object_attributes && @content_length || head[:content_length]
end
# @note S3 does not compute content-type. It reports the content-type
# as was reported during the file upload.
# @return [String] Returns the content type as reported by S3,
# defaults to an empty string when not provided during upload.
def content_type
head[:content_type]
end
# @return [DateTime,nil]
def expiration_date
head[:expiration_date]
end
# @return [String,nil]
def expiration_rule_id
head[:expiration_rule_id]
end
# @return [Symbol, nil] Returns the algorithm used to encrypt
# the object on the server side, or `nil` if SSE was not used
# when storing the object.
def server_side_encryption
head[:server_side_encryption]
end
# @return [true, false] Returns true if the object was stored
# using server side encryption.
def server_side_encryption?
!server_side_encryption.nil?
end
# @return [Boolean] whether a {#restore} operation on the
# object is currently being performed on the object.
# @see #restore_expiration_date
# @since 1.7.2
def restore_in_progress?
head[:restore_in_progress]
end
# @return [DateTime] the time when the temporarily restored object
# will be removed from S3. Note that the original object will remain
# available in Glacier.
# @return [nil] if the object was not restored from an archived
# copy
# @since 1.7.2
def restore_expiration_date
head[:restore_expiration_date]
end
# @return [Boolean] whether the object is a temporary copy of an
# archived object in the Glacier storage class.
# @since 1.7.2
def restored_object?
!!head[:restore_expiration_date]
end
# Deletes the object from its S3 bucket.
#
# @param [Hash] options
#
# @option [String] :version_id (nil) If present the specified version
# of this object will be deleted. Only works for buckets that have
# had versioning enabled.
#
# @option [Boolean] :delete_instruction_file (false) Set this to `true`
# if you use client-side encryption and the encryption materials
# were stored in a separate object in S3 (key.instruction).
#
# @option [String] :mfa The serial number and current token code of
# the Multi-Factor Authentication (MFA) device for the user. Format
# is "SERIAL TOKEN" - with a space between the serial and token.
#
# @return [nil]
def delete options = {}
client.delete_object(options.merge(
:bucket_name => bucket.name,
:key => key))
if options[:delete_instruction_file]
client.delete_object(
:bucket_name => bucket.name,
:key => key + '.instruction')
end
nil
end
# Restores a temporary copy of an archived object from the
# Glacier storage tier. After the specified `days`, Amazon
# S3 deletes the temporary copy. Note that the object
# remains archived; Amazon S3 deletes only the restored copy.
#
# Restoring an object does not occur immediately. Use
# {#restore_in_progress?} to check the status of the operation.
#
# @option [Integer] :days (1) the number of days to keep the object
# @return [Boolean] `true` if a restore can be initiated.
# @since 1.7.2
def restore options = {}
options[:days] ||= 1
client.restore_object(options.merge({
:bucket_name => bucket.name,
:key => key,
}))
true
end
# @option [String] :version_id (nil) If present the metadata object
# will be for the specified version.
# @return [ObjectMetadata] Returns an instance of ObjectMetadata
# representing the metadata for this object.
def metadata options = {}
options[:config] = config
ObjectMetadata.new(self, options)
end
# Returns a collection representing all the object versions
# for this object.
#
# @example
#
# bucket.versioning_enabled? # => true
# version = bucket.objects["mykey"].versions.latest
#
# @return [ObjectVersionCollection]
def versions
ObjectVersionCollection.new(self)
end
# Uploads data to the object in S3.
#
# obj = s3.buckets['bucket-name'].objects['key']
#
# # strings
# obj.write("HELLO")
#
# # files (by path)
# obj.write(Pathname.new('path/to/file.txt'))
#
# # file objects
# obj.write(File.open('path/to/file.txt', 'rb'))
#
# # IO objects (must respond to #read and #eof?)
# obj.write(io)
#
# ### Multipart Uploads vs Single Uploads
#
# This method will intelligently choose between uploading the
# file in a signal request and using {#multipart_upload}.
# You can control this behavior by configuring the thresholds
# and you can disable the multipart feature as well.
#
# # always send the file in a single request
# obj.write(file, :single_request => true)
#
# # upload the file in parts if the total file size exceeds 100MB
# obj.write(file, :multipart_threshold => 100 * 1024 * 1024)
#
# @overload write(data, options = {})
#
# @param [String,Pathname,File,IO] data The data to upload.
# This may be a:
# * String
# * Pathname
# * File
# * IO
# * Any object that responds to `#read` and `#eof?`.
#
# @param options [Hash] Additional upload options.
#
# @option options [Integer] :content_length If provided, this
# option must match the total number of bytes written to S3.
# This options is *required* when it is not possible to
# automatically determine the size of `data`.
#
# @option options [Integer] :estimated_content_length When uploading
# data of unknown content length, you may specify this option to
# hint what mode of upload should take place. When
# `:estimated_content_length` exceeds the `:multipart_threshold`,
# then the data will be uploaded in parts, otherwise it will
# be read into memory and uploaded via {Client#put_object}.
#
# @option options [Boolean] :single_request (false) When `true`,
# this method will always upload the data in a single request
# (via {Client#put_object}). When `false`, this method will
# choose between {Client#put_object} and {#multipart_upload}.
#
# @option options [Integer] :multipart_threshold (16777216) Specifies
# the maximum size (in bytes) of a single-request upload. If the
# data exceeds this threshold, it will be uploaded via
# {#multipart_upload}. The default threshold is 16MB and can
# be configured via AWS.config(:s3_multipart_threshold => ...).
#
# @option options [Integer] :multipart_min_part_size (5242880) The
# minimum size of a part to upload to S3 when using
# {#multipart_upload}. S3 will reject parts smaller than 5MB
# (except the final part). The default is 5MB and can be
# configured via AWS.config(:s3_multipart_min_part_size => ...).
#
# @option options [Hash] :metadata A hash of metadata to be
# included with the object. These will be sent to S3 as
# headers prefixed with `x-amz-meta`. Each name, value pair
# must conform to US-ASCII.
#
# @option options [Symbol,String] :acl (:private) A canned access
# control policy. Valid values are:
#
# * `:private`
# * `:public_read`
# * `:public_read_write`
# * `:authenticated_read`
# * `:bucket_owner_read`
# * `:bucket_owner_full_control`
#
# @option options [String] :grant_read
#
# @option options [String] :grant_write
#
# @option options [String] :grant_read_acp
#
# @option options [String] :grant_write_acp
#
# @option options [String] :grant_full_control
#
# @option options [Boolean] :reduced_redundancy (false) When `true`,
# this object will be stored with Reduced Redundancy Storage.
#
# @option options :cache_control [String] Can be used to specify
# caching behavior. See
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
#
# @option options :content_disposition [String] Specifies
# presentational information for the object. See
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1
#
# @option options :content_encoding [String] Specifies what
# content encodings have been applied to the object and thus
# what decoding mechanisms must be applied to obtain the
# media-type referenced by the `Content-Type` header field.
# See
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
#
# @option options [String] :content_md5
# The base64 encoded content md5 of the data.
#
# @option options :content_type A standard MIME type
# describing the format of the object data.
#
# @option options [Symbol] :server_side_encryption (nil) If this
# option is set, the object will be stored using server side
# encryption. The only valid value is `:aes256`, which
# specifies that the object should be stored using the AES
# encryption algorithm with 256 bit keys. By default, this
# option uses the value of the `:s3_server_side_encryption`
# option in the current configuration; for more information,
# see {AWS.config}.
#
# @option options [OpenSSL::PKey::RSA, String] :encryption_key
# Set this to encrypt the data client-side using envelope
# encryption. The key must be an OpenSSL asymmetric key
# or a symmetric key string (16, 24 or 32 bytes in length).
#
# @option options [Symbol] :encryption_materials_location (:metadata)
# Set this to `:instruction_file` if you prefer to store the
# client-side encryption materials in a separate object in S3
# instead of in the object metadata.
#
# @option options [String] :expires The date and time at which the
# object is no longer cacheable.
#
# @option options [String] :website_redirect_location
#
# @return [S3Object, ObjectVersion] If the bucket has versioning
# enabled, this methods returns an {ObjectVersion}, otherwise
# this method returns `self`.
#
def write *args, &block
options = compute_write_options(*args, &block)
add_storage_class_option(options)
add_sse_options(options)
add_cse_options(options)
if use_multipart?(options)
write_with_multipart(options)
else
write_with_put_object(options)
end
end
# Performs a multipart upload. Use this if you have specific
# needs for how the upload is split into parts, or if you want
# to have more control over how the failure of an individual
# part upload is handled. Otherwise, {#write} is much simpler
# to use.
#
# Note: After you initiate multipart upload and upload one or
# more parts, you must either complete or abort multipart
# upload in order to stop getting charged for storage of the
# uploaded parts. Only after you either complete or abort
# multipart upload, Amazon S3 frees up the parts storage and
# stops charging you for the parts storage.
#
# @example Uploading an object in two parts
#
# bucket.objects.myobject.multipart_upload do |upload|
# upload.add_part("a" * 5242880)
# upload.add_part("b" * 2097152)
# end
#
# @example Uploading parts out of order
#
# bucket.objects.myobject.multipart_upload do |upload|
# upload.add_part("b" * 2097152, :part_number => 2)
# upload.add_part("a" * 5242880, :part_number => 1)
# end
#
# @example Aborting an upload after parts have been added
#
# bucket.objects.myobject.multipart_upload do |upload|
# upload.add_part("b" * 2097152, :part_number => 2)
# upload.abort
# end
#
# @example Starting an upload and completing it later by ID
#
# upload = bucket.objects.myobject.multipart_upload
# upload.add_part("a" * 5242880)
# upload.add_part("b" * 2097152)
# id = upload.id
#
# # later or in a different process
# upload = bucket.objects.myobject.multipart_uploads[id]
# upload.complete(:remote_parts)
#
# @yieldparam [MultipartUpload] upload A handle to the upload.
# {MultipartUpload#close} is called in an `ensure` clause so
# that the upload will always be either completed or
# aborted.
#
# @param [Hash] options Options for the upload.
#
# @option options [Hash] :metadata A hash of metadata to be
# included with the object. These will be sent to S3 as
# headers prefixed with `x-amz-meta`. Each name, value pair
# must conform to US-ASCII.
#
# @option options [Symbol] :acl (private) A canned access
# control policy. Valid values are:
#
# * `:private`
# * `:public_read`
# * `:public_read_write`
# * `:authenticated_read`
# * `:bucket_owner_read`
# * `:bucket_owner_full_control`
#
# @option options [Boolean] :reduced_redundancy (false) If true,
# Reduced Redundancy Storage will be enabled for the uploaded
# object.
#
# @option options :cache_control [String] Can be used to specify
# caching behavior. See
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
#
# @option options :content_disposition [String] Specifies
# presentational information for the object. See
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec19.5.1
#
# @option options :content_encoding [String] Specifies what
# content encodings have been applied to the object and thus
# what decoding mechanisms must be applied to obtain the
# media-type referenced by the `Content-Type` header field.
# See
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
#
# @option options :content_type A standard MIME type
# describing the format of the object data.
#
# @option options [Symbol] :server_side_encryption (nil) If this
# option is set, the object will be stored using server side
# encryption. The only valid value is `:aes256`, which
# specifies that the object should be stored using the AES
# encryption algorithm with 256 bit keys. By default, this
# option uses the value of the `:s3_server_side_encryption`
# option in the current configuration; for more information,
# see {AWS.config}.
#
# @return [S3Object, ObjectVersion] If the bucket has versioning
# enabled, returns the {ObjectVersion} representing the
# version that was uploaded. If versioning is disabled,
# returns self.
#
def multipart_upload(options = {})
options = options.dup
add_sse_options(options)
upload = multipart_uploads.create(options)
if block_given?
begin
yield(upload)
upload.close
rescue => e
upload.abort
raise e
end
else
upload
end
end
# @example Abort any in-progress uploads for the object:
#
# object.multipart_uploads.each(&:abort)
#
# @return [ObjectUploadCollection] Returns an object representing the
# collection of uploads that are in progress for this object.
def multipart_uploads
ObjectUploadCollection.new(self)
end
# Moves an object to a new key.
#
# This works by copying the object to a new key and then
# deleting the old object. This function returns the
# new object once this is done.
#
# bucket = s3.buckets['old-bucket']
# old_obj = bucket.objects['old-key']
#
# # renaming an object returns a new object
# new_obj = old_obj.move_to('new-key')
#
# old_obj.key #=> 'old-key'
# old_obj.exists? #=> false
#
# new_obj.key #=> 'new-key'
# new_obj.exists? #=> true
#
# If you need to move an object to a different bucket, pass
# `:bucket` or `:bucket_name`.
#
# obj = s3.buckets['old-bucket'].objects['old-key']
# obj.move_to('new-key', :bucket_name => 'new_bucket')
#
# If the copy succeeds, but the then the delete fails, an error
# will be raised.
#
# @param [String] target The key to move this object to.
#
# @param [Hash] options
#
# @option (see #copy_to)
#
# @return [S3Object] Returns a new object with the new key.
#
def move_to target, options = {}
copy = copy_to(target, options)
delete
copy
end
alias_method :rename_to, :move_to
# Copies data from one S3 object to another.
#
# S3 handles the copy so the clients does not need to fetch the data
# and upload it again. You can also change the storage class and
# metadata of the object when copying.
#
# @note This operation does not copy the ACL, storage class
# (standard vs. reduced redundancy) or server side encryption
# setting from the source object. If you don't specify any of
# these options when copying, the object will have the default
# values as described below.
#
# @param [Mixed] source
#
# @param [Hash] options
#
# @option options [String] :bucket_name The slash-prefixed name of
# the bucket the source object can be found in. Defaults to the
# current object's bucket.
#
# @option options [Bucket] :bucket The bucket the source object
# can be found in. Defaults to the current object's bucket.
#
# @option options [Hash] :metadata A hash of metadata to save
# with the copied object. Each name, value pair must conform
# to US-ASCII. When blank, the sources metadata is copied.
# If you set this value, you must set ALL metadata values for
# the object as we do not preserve existing values.
#
# @option options [String] :content_type The content type of
# the copied object. Defaults to the source object's content
# type.
#
# @option options [String] :content_disposition The presentational
# information for the object. Defaults to the source object's
# content disposition.
#
# @option options [Boolean] :reduced_redundancy (false) If true the
# object is stored with reduced redundancy in S3 for a lower cost.
#
# @option options [String] :version_id (nil) Causes the copy to
# read a specific version of the source object.
#
# @option options [Symbol] :acl (private) A canned access
# control policy. Valid values are:
#
# * `:private`
# * `:public_read`
# * `:public_read_write`
# * `:authenticated_read`
# * `:bucket_owner_read`
# * `:bucket_owner_full_control`
#
# @option options [Symbol] :server_side_encryption (nil) If this
# option is set, the object will be stored using server side
# encryption. The only valid value is `:aes256`, which
# specifies that the object should be stored using the AES
# encryption algorithm with 256 bit keys. By default, this
# option uses the value of the `:s3_server_side_encryption`
# option in the current configuration; for more information,
# see {AWS.config}.
#
# @option options [Boolean] :client_side_encrypted (false) Set to true
# when the object being copied was client-side encrypted. This
# is important so the encryption metadata will be copied.
#
# @option options [Boolean] :use_multipart_copy (false) Set this to
# `true` if you need to copy an object that is larger than 5GB.
#
# @option options :cache_control [String] Can be used to specify
# caching behavior. See
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
#
# @option options [String] :expires The date and time at which the
# object is no longer cacheable.
#
# @return [nil]
def copy_from source, options = {}
options = options.dup
options[:copy_source] =
case source
when S3Object
"/#{source.bucket.name}/#{source.key}"
when ObjectVersion
options[:version_id] = source.version_id
"/#{source.object.bucket.name}/#{source.object.key}"
else
if options[:bucket]
"/#{options.delete(:bucket).name}/#{source}"
elsif options[:bucket_name]
# oops, this should be slash-prefixed, but unable to change
# this without breaking users that already work-around this
# bug by sending :bucket_name => "/bucket-name"
"#{options.delete(:bucket_name)}/#{source}"
else
"/#{self.bucket.name}/#{source}"
end
end
if [:metadata, :content_disposition, :content_type, :cache_control,
].any? {|opt| options.key?(opt) }
then
options[:metadata_directive] = 'REPLACE'
else
options[:metadata_directive] ||= 'COPY'
end
# copies client-side encryption materials (from the metadata or
# instruction file)
if options.delete(:client_side_encrypted)
copy_cse_materials(source, options)
end
add_sse_options(options)
options[:storage_class] = options.delete(:reduced_redundancy) ?
'REDUCED_REDUNDANCY' : 'STANDARD'
options[:bucket_name] = bucket.name
options[:key] = key
if use_multipart_copy?(options)
multipart_copy(options)
else
resp = client.copy_object(options)
end
nil
end
# Copies data from the current object to another object in S3.
#
# S3 handles the copy so the client does not need to fetch the data
# and upload it again. You can also change the storage class and
# metadata of the object when copying.
#
# @note This operation does not copy the ACL, storage class
# (standard vs. reduced redundancy) or server side encryption
# setting from this object to the new object. If you don't
# specify any of these options when copying, the new object
# will have the default values as described below.
#
# @param [S3Object,String] target An S3Object, or a string key of
# and object to copy to.
#
# @param [Hash] options
#
# @option options [String] :bucket_name The slash-prefixed name of the
# bucket the object should be copied into. Defaults to the current
# object's bucket.
#
# @option options [Bucket] :bucket The bucket the target object
# should be copied into. Defaults to the current object's bucket.
#
# @option options [Hash] :metadata A hash of metadata to save
# with the copied object. Each name, value pair must conform
# to US-ASCII. When blank, the sources metadata is copied.
#
# @option options [Boolean] :reduced_redundancy (false) If true
# the object is stored with reduced redundancy in S3 for a
# lower cost.
#
# @option options [Symbol] :acl (private) A canned access
# control policy. Valid values are:
#
# * `:private`
# * `:public_read`
# * `:public_read_write`
# * `:authenticated_read`
# * `:bucket_owner_read`
# * `:bucket_owner_full_control`
#
# @option options [Symbol] :server_side_encryption (nil) If this
# option is set, the object will be stored using server side
# encryption. The only valid value is `:aes256`, which
# specifies that the object should be stored using the AES
# encryption algorithm with 256 bit keys. By default, this
# option uses the value of the `:s3_server_side_encryption`
# option in the current configuration; for more information,
# see {AWS.config}.
#
# @option options [Boolean] :client_side_encrypted (false) When `true`,
# the client-side encryption materials will be copied. Without this
# option, the key and iv are not guaranteed to be transferred to
# the new object.
#
# @option options [String] :expires The date and time at which the
# object is no longer cacheable.
#
# @return [S3Object] Returns the copy (target) object.
#
def copy_to target, options = {}
unless target.is_a?(S3Object)
bucket = case
when options[:bucket] then options[:bucket]
when options[:bucket_name]
Bucket.new(options[:bucket_name], :config => config)
else self.bucket
end
target = S3Object.new(bucket, target)
end
copy_opts = options.dup
copy_opts.delete(:bucket)