ghazel-aws-s3 0.6.4 → 0.6.4.1

Sign up to get free protection for your applications and to get access to all the features.
data/README ADDED
@@ -0,0 +1,542 @@
1
+ = AWS::S3
2
+
3
+ AWS::S3 is a Ruby library for Amazon's Simple Storage Service's REST API (http://aws.amazon.com/s3).
4
+ Full documentation of the currently supported API can be found at http://docs.amazonwebservices.com/AmazonS3/2006-03-01.
5
+
6
+ == Getting started
7
+
8
+ To get started you need to require 'aws/s3':
9
+
10
+ % irb -rubygems
11
+ irb(main):001:0> require 'aws/s3'
12
+ # => true
13
+
14
+ The AWS::S3 library ships with an interactive shell called <tt>s3sh</tt>. From within it, you have access to all the operations the library exposes from the command line.
15
+
16
+ % s3sh
17
+ >> Version
18
+
19
+ Before you can do anything, you must establish a connection using Base.establish_connection!. A basic connection would look something like this:
20
+
21
+ AWS::S3::Base.establish_connection!(
22
+ :access_key_id => 'abc',
23
+ :secret_access_key => '123'
24
+ )
25
+
26
+ The minimum connection options that you must specify are your access key id and your secret access key.
27
+
28
+ (If you don't already have your access keys, all you need to sign up for the S3 service is an account at Amazon. You can sign up for S3 and get access keys by visiting http://aws.amazon.com/s3.)
29
+
30
+ For convenience, if you set two special environment variables with the value of your access keys, the console will automatically create a default connection for you. For example:
31
+
32
+ % cat .amazon_keys
33
+ export AMAZON_ACCESS_KEY_ID='abcdefghijklmnop'
34
+ export AMAZON_SECRET_ACCESS_KEY='1234567891012345'
35
+
36
+ Then load it in your shell's rc file.
37
+
38
+ % cat .zshrc
39
+ if [[ -f "$HOME/.amazon_keys" ]]; then
40
+ source "$HOME/.amazon_keys";
41
+ fi
42
+
43
+ See more connection details at AWS::S3::Connection::Management::ClassMethods.
44
+
45
+
46
+ == AWS::S3 Basics
47
+ === The service, buckets and objects
48
+
49
+ The three main concepts of S3 are the service, buckets and objects.
50
+
51
+ ==== The service
52
+
53
+ The service lets you find out general information about your account, like what buckets you have.
54
+
55
+ Service.buckets
56
+ # => []
57
+
58
+
59
+ ==== Buckets
60
+
61
+ Buckets are containers for objects (the files you store on S3). To create a new bucket you just specify its name.
62
+
63
+ # Pick a unique name, or else you'll get an error
64
+ # if the name is already taken.
65
+ Bucket.create('jukebox')
66
+
67
+ Bucket names must be unique across the entire S3 system, sort of like domain names across the internet. If you try
68
+ to create a bucket with a name that is already taken, you will get an error.
69
+
70
+ Assuming the name you chose isn't already taken, your new bucket will now appear in the bucket list:
71
+
72
+ Service.buckets
73
+ # => [#<AWS::S3::Bucket @attributes={"name"=>"jukebox"}>]
74
+
75
+ Once you have succesfully created a bucket you can you can fetch it by name using Bucket.find.
76
+
77
+ music_bucket = Bucket.find('jukebox')
78
+
79
+ The bucket that is returned will contain a listing of all the objects in the bucket.
80
+
81
+ music_bucket.objects.size
82
+ # => 0
83
+
84
+ If all you are interested in is the objects of the bucket, you can get to them directly using Bucket.objects.
85
+
86
+ Bucket.objects('jukebox').size
87
+ # => 0
88
+
89
+ By default all objects will be returned, though there are several options you can use to limit what is returned, such as
90
+ specifying that only objects whose name is after a certain place in the alphabet be returned, and etc. Details about these options can
91
+ be found in the documentation for Bucket.find.
92
+
93
+ To add an object to a bucket you specify the name of the object, its value, and the bucket to put it in.
94
+
95
+ file = 'black-flowers.mp3'
96
+ S3Object.store(file, open(file), 'jukebox')
97
+
98
+ You'll see your file has been added to it:
99
+
100
+ music_bucket.objects
101
+ # => [#<AWS::S3::S3Object '/jukebox/black-flowers.mp3'>]
102
+
103
+ You can treat your bucket like a hash and access objects by name:
104
+
105
+ jukebox['black-flowers.mp3']
106
+ # => #<AWS::S3::S3Object '/jukebox/black-flowers.mp3'>
107
+
108
+ In the event that you want to delete a bucket, you can use Bucket.delete.
109
+
110
+ Bucket.delete('jukebox')
111
+
112
+ Keep in mind, like unix directories, you can not delete a bucket unless it is empty. Trying to delete a bucket
113
+ that contains objects will raise a BucketNotEmpty exception.
114
+
115
+ Passing the :force => true option to delete will take care of deleting all the bucket's objects for you.
116
+
117
+ Bucket.delete('photos', :force => true)
118
+ # => true
119
+
120
+
121
+ ==== Objects
122
+
123
+ S3Objects represent the data you store on S3. They have a key (their name) and a value (their data). All objects belong to a
124
+ bucket.
125
+
126
+ You can store an object on S3 by specifying a key, its data and the name of the bucket you want to put it in:
127
+
128
+ S3Object.store('me.jpg', open('headshot.jpg'), 'photos')
129
+
130
+ The content type of the object will be inferred by its extension. If the appropriate content type can not be inferred, S3 defaults
131
+ to <tt>binary/octet-stream</tt>.
132
+
133
+ If you want to override this, you can explicitly indicate what content type the object should have with the <tt>:content_type</tt> option:
134
+
135
+ file = 'black-flowers.m4a'
136
+ S3Object.store(
137
+ file,
138
+ open(file),
139
+ 'jukebox',
140
+ :content_type => 'audio/mp4a-latm'
141
+ )
142
+
143
+ You can read more about storing files on S3 in the documentation for S3Object.store.
144
+
145
+ If you just want to fetch an object you've stored on S3, you just specify its name and its bucket:
146
+
147
+ picture = S3Object.find 'headshot.jpg', 'photos'
148
+
149
+ N.B. The actual data for the file is not downloaded in both the example where the file appeared in the bucket and when fetched directly.
150
+ You get the data for the file like this:
151
+
152
+ picture.value
153
+
154
+ You can fetch just the object's data directly:
155
+
156
+ S3Object.value 'headshot.jpg', 'photos'
157
+
158
+ Or stream it by passing a block to <tt>stream</tt>:
159
+
160
+ open('song.mp3', 'w') do |file|
161
+ S3Object.stream('song.mp3', 'jukebox') do |chunk|
162
+ file.write chunk
163
+ end
164
+ end
165
+
166
+ The data of the file, once download, is cached, so subsequent calls to <tt>value</tt> won't redownload the file unless you
167
+ tell the object to reload its <tt>value</tt>:
168
+
169
+ # Redownloads the file's data
170
+ song.value(:reload)
171
+
172
+ Other functionality includes:
173
+
174
+ # Check if an object exists?
175
+ S3Object.exists? 'headshot.jpg', 'photos'
176
+
177
+ # Copying an object
178
+ S3Object.copy 'headshot.jpg', 'headshot2.jpg', 'photos'
179
+
180
+ # Renaming an object
181
+ S3Object.rename 'headshot.jpg', 'portrait.jpg', 'photos'
182
+
183
+ # Deleting an object
184
+ S3Object.delete 'headshot.jpg', 'photos'
185
+
186
+ ==== More about objects and their metadata
187
+
188
+ You can find out the content type of your object with the <tt>content_type</tt> method:
189
+
190
+ song.content_type
191
+ # => "audio/mpeg"
192
+
193
+ You can change the content type as well if you like:
194
+
195
+ song.content_type = 'application/pdf'
196
+ song.store
197
+
198
+ A bevie of information about an object can be had using the <tt>about</tt> method:
199
+
200
+ pp song.about
201
+ {"last-modified" => "Sat, 28 Oct 2006 21:29:26 GMT",
202
+ "content-type" => "binary/octet-stream",
203
+ "etag" => "\"dc629038ffc674bee6f62eb64ff3a\"",
204
+ "date" => "Sat, 28 Oct 2006 21:30:41 GMT",
205
+ "x-amz-request-id" => "B7BC68F55495B1C8",
206
+ "server" => "AmazonS3",
207
+ "content-length" => "3418766"}
208
+
209
+ You can get and set metadata for an object:
210
+
211
+ song.metadata
212
+ # => {}
213
+ song.metadata[:album] = "A River Ain't Too Much To Love"
214
+ # => "A River Ain't Too Much To Love"
215
+ song.metadata[:released] = 2005
216
+ pp song.metadata
217
+ {"x-amz-meta-released" => 2005,
218
+ "x-amz-meta-album" => "A River Ain't Too Much To Love"}
219
+ song.store
220
+
221
+ That metadata will be saved in S3 and is hence forth available from that object:
222
+
223
+ song = S3Object.find('black-flowers.mp3', 'jukebox')
224
+ pp song.metadata
225
+ {"x-amz-meta-released" => "2005",
226
+ "x-amz-meta-album" => "A River Ain't Too Much To Love"}
227
+ song.metadata[:released]
228
+ # => "2005"
229
+ song.metadata[:released] = 2006
230
+ pp song.metadata
231
+ {"x-amz-meta-released" => 2006,
232
+ "x-amz-meta-album" => "A River Ain't Too Much To Love"}
233
+
234
+
235
+ ==== Streaming uploads
236
+
237
+ When storing an object on the S3 servers using S3Object.store, the <tt>data</tt> argument can be a string or an I/O stream.
238
+ If <tt>data</tt> is an I/O stream it will be read in segments and written to the socket incrementally. This approach
239
+ may be desirable for very large files so they are not read into memory all at once.
240
+
241
+ # Non streamed upload
242
+ S3Object.store('greeting.txt', 'hello world!', 'marcel')
243
+
244
+ # Streamed upload
245
+ S3Object.store('roots.mpeg', open('roots.mpeg'), 'marcel')
246
+
247
+
248
+ == Setting the current bucket
249
+ ==== Scoping operations to a specific bucket
250
+
251
+ If you plan on always using a specific bucket for certain files, you can skip always having to specify the bucket by creating
252
+ a subclass of Bucket or S3Object and telling it what bucket to use:
253
+
254
+ class JukeBoxSong < AWS::S3::S3Object
255
+ set_current_bucket_to 'jukebox'
256
+ end
257
+
258
+ For all methods that take a bucket name as an argument, the current bucket will be used if the bucket name argument is omitted.
259
+
260
+ other_song = 'baby-please-come-home.mp3'
261
+ JukeBoxSong.store(other_song, open(other_song))
262
+
263
+ This time we didn't have to explicitly pass in the bucket name, as the JukeBoxSong class knows that it will
264
+ always use the 'jukebox' bucket.
265
+
266
+ "Astute readers", as they say, may have noticed that we used the third parameter to pass in the content type,
267
+ rather than the fourth parameter as we had the last time we created an object. If the bucket can be inferred, or
268
+ is explicitly set, as we've done in the JukeBoxSong class, then the third argument can be used to pass in
269
+ options.
270
+
271
+ Now all operations that would have required a bucket name no longer do.
272
+
273
+ other_song = JukeBoxSong.find('baby-please-come-home.mp3')
274
+
275
+
276
+ == BitTorrent
277
+ ==== Another way to download large files
278
+
279
+ Objects on S3 can be distributed via the BitTorrent file sharing protocol.
280
+
281
+ You can get a torrent file for an object by calling <tt>torrent_for</tt>:
282
+
283
+ S3Object.torrent_for 'kiss.jpg', 'marcel'
284
+
285
+ Or just call the <tt>torrent</tt> method if you already have the object:
286
+
287
+ song = S3Object.find 'kiss.jpg', 'marcel'
288
+ song.torrent
289
+
290
+ Calling <tt>grant_torrent_access_to</tt> on a object will allow anyone to anonymously
291
+ fetch the torrent file for that object:
292
+
293
+ S3Object.grant_torrent_access_to 'kiss.jpg', 'marcel'
294
+
295
+ Anonymous requests to
296
+
297
+ http://s3.amazonaws.com/marcel/kiss.jpg?torrent
298
+
299
+ will serve up the torrent file for that object.
300
+
301
+
302
+ == Access control
303
+ ==== Using canned access control policies
304
+
305
+ By default buckets are private. This means that only the owner has access rights to the bucket and its objects.
306
+ Objects in that bucket inherit the permission of the bucket unless otherwise specified. When an object is private, the owner can
307
+ generate a signed url that exposes the object to anyone who has that url. Alternatively, buckets and objects can be given other
308
+ access levels. Several canned access levels are defined:
309
+
310
+ * <tt>:private</tt> - Owner gets FULL_CONTROL. No one else has any access rights. This is the default.
311
+ * <tt>:public_read</tt> - Owner gets FULL_CONTROL and the anonymous principal is granted READ access. If this policy is used on an object, it can be read from a browser with no authentication.
312
+ * <tt>:public_read_write</tt> - Owner gets FULL_CONTROL, the anonymous principal is granted READ and WRITE access. This is a useful policy to apply to a bucket, if you intend for any anonymous user to PUT objects into the bucket.
313
+ * <tt>:authenticated_read</tt> - Owner gets FULL_CONTROL, and any principal authenticated as a registered Amazon S3 user is granted READ access.
314
+
315
+ You can set a canned access level when you create a bucket or an object by using the <tt>:access</tt> option:
316
+
317
+ S3Object.store(
318
+ 'kiss.jpg',
319
+ data,
320
+ 'marcel',
321
+ :access => :public_read
322
+ )
323
+
324
+ Since the image we created is publicly readable, we can access it directly from a browser by going to the corresponding bucket name
325
+ and specifying the object's key without a special authenticated url:
326
+
327
+ http://s3.amazonaws.com/marcel/kiss.jpg
328
+
329
+ ==== Building custum access policies
330
+
331
+ For both buckets and objects, you can use the <tt>acl</tt> method to see its access control policy:
332
+
333
+ policy = S3Object.acl('kiss.jpg', 'marcel')
334
+ pp policy.grants
335
+ [#<AWS::S3::ACL::Grant FULL_CONTROL to noradio>,
336
+ #<AWS::S3::ACL::Grant READ to AllUsers Group>]
337
+
338
+ Policies are made up of one or more grants which grant a specific permission to some grantee. Here we see the default FULL_CONTROL grant
339
+ to the owner of this object. There is also READ permission granted to the Allusers Group, which means anyone has read access for the object.
340
+
341
+ Say we wanted to grant access to anyone to read the access policy of this object. The current READ permission only grants them permission to read
342
+ the object itself (for example, from a browser) but it does not allow them to read the access policy. For that we will need to grant the AllUsers group the READ_ACP permission.
343
+
344
+ First we'll create a new grant object:
345
+
346
+ grant = ACL::Grant.new
347
+ # => #<AWS::S3::ACL::Grant (permission) to (grantee)>
348
+ grant.permission = 'READ_ACP'
349
+
350
+ Now we need to indicate who this grant is for. In other words, who the grantee is:
351
+
352
+ grantee = ACL::Grantee.new
353
+ # => #<AWS::S3::ACL::Grantee (xsi not set yet)>
354
+
355
+ There are three ways to specify a grantee: 1) by their internal amazon id, such as the one returned with an object's Owner,
356
+ 2) by their Amazon account email address or 3) by specifying a group. As of this writing you can not create custom groups, but
357
+ Amazon does provide three already: AllUsers, Authenticated and LogDelivery. In this case we want to provide the grant to all users.
358
+ This effectively means "anyone".
359
+
360
+ grantee.group = 'AllUsers'
361
+
362
+ Now that our grantee is setup, we'll associate it with the grant:
363
+
364
+ grant.grantee = grantee
365
+ grant
366
+ # => #<AWS::S3::ACL::Grant READ_ACP to AllUsers Group>
367
+
368
+ Are grant has all the information we need. Now that it's ready, we'll add it on to the object's access control policy's list of grants:
369
+
370
+ policy.grants << grant
371
+ pp policy.grants
372
+ [#<AWS::S3::ACL::Grant FULL_CONTROL to noradio>,
373
+ #<AWS::S3::ACL::Grant READ to AllUsers Group>,
374
+ #<AWS::S3::ACL::Grant READ_ACP to AllUsers Group>]
375
+
376
+ Now that the policy has the new grant, we reuse the <tt>acl</tt> method to persist the policy change:
377
+
378
+ S3Object.acl('kiss.jpg', 'marcel', policy)
379
+
380
+ If we fetch the object's policy again, we see that the grant has been added:
381
+
382
+ pp S3Object.acl('kiss.jpg', 'marcel').grants
383
+ [#<AWS::S3::ACL::Grant FULL_CONTROL to noradio>,
384
+ #<AWS::S3::ACL::Grant READ to AllUsers Group>,
385
+ #<AWS::S3::ACL::Grant READ_ACP to AllUsers Group>]
386
+
387
+ If we were to access this object's acl url from a browser:
388
+
389
+ http://s3.amazonaws.com/marcel/kiss.jpg?acl
390
+
391
+ we would be shown its access control policy.
392
+
393
+ ==== Pre-prepared grants
394
+
395
+ Alternatively, the ACL::Grant class defines a set of stock grant policies that you can fetch by name. In most cases, you can
396
+ just use one of these pre-prepared grants rather than building grants by hand. Two of these stock policies are <tt>:public_read</tt>
397
+ and <tt>:public_read_acp</tt>, which happen to be the two grants that we built by hand above. In this case we could have simply written:
398
+
399
+ policy.grants << ACL::Grant.grant(:public_read)
400
+ policy.grants << ACL::Grant.grant(:public_read_acp)
401
+ S3Object.acl('kiss.jpg', 'marcel', policy)
402
+
403
+ The full details can be found in ACL::Policy, ACL::Grant and ACL::Grantee.
404
+
405
+
406
+ ==== Accessing private objects from a browser
407
+
408
+ All private objects are accessible via an authenticated GET request to the S3 servers. You can generate an
409
+ authenticated url for an object like this:
410
+
411
+ S3Object.url_for('beluga_baby.jpg', 'marcel_molina')
412
+
413
+ By default authenticated urls expire 5 minutes after they were generated.
414
+
415
+ Expiration options can be specified either with an absolute time since the epoch with the <tt>:expires</tt> options,
416
+ or with a number of seconds relative to now with the <tt>:expires_in</tt> options:
417
+
418
+ # Absolute expiration date
419
+ # (Expires January 18th, 2038)
420
+ doomsday = Time.mktime(2038, 1, 18).to_i
421
+ S3Object.url_for('beluga_baby.jpg',
422
+ 'marcel',
423
+ :expires => doomsday)
424
+
425
+ # Expiration relative to now specified in seconds
426
+ # (Expires in 3 hours)
427
+ S3Object.url_for('beluga_baby.jpg',
428
+ 'marcel',
429
+ :expires_in => 60 * 60 * 3)
430
+
431
+ You can specify whether the url should go over SSL with the <tt>:use_ssl</tt> option:
432
+
433
+ # Url will use https protocol
434
+ S3Object.url_for('beluga_baby.jpg',
435
+ 'marcel',
436
+ :use_ssl => true)
437
+
438
+ By default, the ssl settings for the current connection will be used.
439
+
440
+ If you have an object handy, you can use its <tt>url</tt> method with the same objects:
441
+
442
+ song.url(:expires_in => 30)
443
+
444
+ To get an unauthenticated url for the object, such as in the case
445
+ when the object is publicly readable, pass the
446
+ <tt>:authenticated</tt> option with a value of <tt>false</tt>.
447
+
448
+ S3Object.url_for('beluga_baby.jpg',
449
+ 'marcel',
450
+ :authenticated => false)
451
+ # => http://s3.amazonaws.com/marcel/beluga_baby.jpg
452
+
453
+
454
+ == Logging
455
+ ==== Tracking requests made on a bucket
456
+
457
+ A bucket can be set to log the requests made on it. By default logging is turned off. You can check if a bucket has logging enabled:
458
+
459
+ Bucket.logging_enabled_for? 'jukebox'
460
+ # => false
461
+
462
+ Enabling it is easy:
463
+
464
+ Bucket.enable_logging_for('jukebox')
465
+
466
+ Unless you specify otherwise, logs will be written to the bucket you want to log. The logs are just like any other object. By default they will start with the prefix 'log-'. You can customize what bucket you want the logs to be delivered to, as well as customize what the log objects' key is prefixed with by setting the <tt>target_bucket</tt> and <tt>target_prefix</tt> option:
467
+
468
+ Bucket.enable_logging_for(
469
+ 'jukebox', 'target_bucket' => 'jukebox-logs'
470
+ )
471
+
472
+ Now instead of logging right into the jukebox bucket, the logs will go into the bucket called jukebox-logs.
473
+
474
+ Once logs have accumulated, you can access them using the <tt>logs</tt> method:
475
+
476
+ pp Bucket.logs('jukebox')
477
+ [#<AWS::S3::Logging::Log '/jukebox-logs/log-2006-11-14-07-15-24-2061C35880A310A1'>,
478
+ #<AWS::S3::Logging::Log '/jukebox-logs/log-2006-11-14-08-15-27-D8EEF536EC09E6B3'>,
479
+ #<AWS::S3::Logging::Log '/jukebox-logs/log-2006-11-14-08-15-29-355812B2B15BD789'>]
480
+
481
+ Each log has a <tt>lines</tt> method that gives you information about each request in that log. All the fields are available
482
+ as named methods. More information is available in Logging::Log::Line.
483
+
484
+ logs = Bucket.logs('jukebox')
485
+ log = logs.first
486
+ line = log.lines.first
487
+ line.operation
488
+ # => 'REST.GET.LOGGING_STATUS'
489
+ line.request_uri
490
+ # => 'GET /jukebox?logging HTTP/1.1'
491
+ line.remote_ip
492
+ # => "67.165.183.125"
493
+
494
+ Disabling logging is just as simple as enabling it:
495
+
496
+ Bucket.disable_logging_for('jukebox')
497
+
498
+
499
+ == Errors
500
+ ==== When things go wrong
501
+
502
+ Anything you do that makes a request to S3 could result in an error. If it does, the AWS::S3 library will raise an exception
503
+ specific to the error. All exception that are raised as a result of a request returning an error response inherit from the
504
+ ResponseError exception. So should you choose to rescue any such exception, you can simple rescue ResponseError.
505
+
506
+ Say you go to delete a bucket, but the bucket turns out to not be empty. This results in a BucketNotEmpty error (one of the many
507
+ errors listed at http://docs.amazonwebservices.com/AmazonS3/2006-03-01/ErrorCodeList.html):
508
+
509
+ begin
510
+ Bucket.delete('jukebox')
511
+ rescue ResponseError => error
512
+ # ...
513
+ end
514
+
515
+ Once you've captured the exception, you can extract the error message from S3, as well as the full error response, which includes
516
+ things like the HTTP response code:
517
+
518
+ error
519
+ # => #<AWS::S3::BucketNotEmpty The bucket you tried to delete is not empty>
520
+ error.message
521
+ # => "The bucket you tried to delete is not empty"
522
+ error.response.code
523
+ # => 409
524
+
525
+ You could use this information to redisplay the error in a way you see fit, or just to log the error and continue on.
526
+
527
+
528
+ ==== Accessing the last request's response
529
+
530
+ Sometimes methods that make requests to the S3 servers return some object, like a Bucket or an S3Object.
531
+ Othertimes they return just <tt>true</tt>. Other times they raise an exception that you may want to rescue. Despite all these
532
+ possible outcomes, every method that makes a request stores its response object for you in Service.response. You can always
533
+ get to the last request's response via Service.response.
534
+
535
+ objects = Bucket.objects('jukebox')
536
+ Service.response.success?
537
+ # => true
538
+
539
+ This is also useful when an error exception is raised in the console which you weren't expecting. You can
540
+ root around in the response to get more details of what might have gone wrong.
541
+
542
+