forked from marcel/aws-s3
-
Notifications
You must be signed in to change notification settings - Fork 17
/
README
443 lines (293 loc) · 16.3 KB
/
README
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
= Aliyun::OSS
Aliyun::OSS is a Ruby library for Aliyun's Simple Storage Service's REST API (http://www.aliyun.com/product/oss).
Full documentation of the currently supported API can be found at http://www.aliyun.com/product/oss#resources.
== Getting started
To get started you need to require 'aliyun/oss':
% irb -rubygems
irb(main):001:0> require 'aliyun/oss'
# => true
The Aliyun::OSS library ships with an interactive shell called <tt>oss</tt>. From within it, you have access to all the operations the library exposes from the command line.
% oss
>> Version
Before you can do anything, you must establish a connection using Base.establish_connection!. A basic connection would look something like this:
Aliyun::OSS::Base.establish_connection!(
:access_key_id => 'abc',
:secret_access_key => '123'
)
The minimum connection options that you must specify are your access key id and your secret access key.
(If you don't already have your access keys, all you need to sign up for the OSS service is an account at Aliyun. You can sign up for OSS and get access keys by visiting http://aliyun.aliyun.com/oss.)
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:
% cat .oss_keys
export OSS_ACCESS_KEY_ID='abcdefghijklmnop'
export OSS_SECRET_ACCESS_KEY='1234567891012345'
Then load it in your shell's rc file.
% cat .zshrc
if [[ -f "$HOME/.oss_keys" ]]; then
source "$HOME/.oss_keys";
fi
See more connection details at Aliyun::OSS::Connection::Management::ClassMethods.
== Aliyun::OSS Basics
=== The service, buckets and objects
The three main concepts of OSS are the service, buckets and objects.
==== The service
The service lets you find out general information about your account, like what buckets you have.
Service.buckets
# => []
==== Buckets
Buckets are containers for objects (the files you store on OSS). To create a new bucket you just specify its name.
# Pick a unique name, or else you'll get an error
# if the name is already taken.
Bucket.create('jukebox')
Bucket names must be unique across the entire OSS system, sort of like domain names across the internet. If you try
to create a bucket with a name that is already taken, you will get an error.
Assuming the name you chose isn't already taken, your new bucket will now appear in the bucket list:
Service.buckets
# => [#<Aliyun::OSS::Bucket @attributes={"name"=>"jukebox"}>]
Once you have succesfully created a bucket you can fetch it by name using Bucket.find.
music_bucket = Bucket.find('jukebox')
The bucket that is returned will contain a listing of all the objects in the bucket.
music_bucket.objects.size
# => 0
If all you are interested in is the objects of the bucket, you can get to them directly using Bucket.objects.
Bucket.objects('jukebox').size
# => 0
By default all objects will be returned, though there are several options you can use to limit what is returned, such as
specifying that only objects whose name is after a certain place in the alphabet be returned, and etc. Details about these options can
be found in the documentation for Bucket.find.
To add an object to a bucket you specify the name of the object, its value, and the bucket to put it in.
file = 'black-flowers.mp3'
OSSObject.store(file, open(file), 'jukebox')
You'll see your file has been added to it:
music_bucket.objects
# => [#<Aliyun::OSS::OSSObject '/jukebox/black-flowers.mp3'>]
You can treat your bucket like a hash and access objects by name:
jukebox['black-flowers.mp3']
# => #<Aliyun::OSS::OSSObject '/jukebox/black-flowers.mp3'>
In the event that you want to delete a bucket, you can use Bucket.delete.
Bucket.delete('jukebox')
Keep in mind, like unix directories, you can not delete a bucket unless it is empty. Trying to delete a bucket
that contains objects will raise a BucketNotEmpty exception.
Passing the :force => true option to delete will take care of deleting all the bucket's objects for you.
Bucket.delete('photos', :force => true)
# => true
==== Objects
OSSObjects represent the data you store on OSS. They have a key (their name) and a value (their data). All objects belong to a
bucket.
You can store an object on OSS by specifying a key, its data and the name of the bucket you want to put it in:
OSSObject.store('me.jpg', open('headshot.jpg'), 'photos')
The content type of the object will be inferred by its extension. If the appropriate content type can not be inferred, OSS defaults
to <tt>binary/octet-stream</tt>.
If you want to override this, you can explicitly indicate what content type the object should have with the <tt>:content_type</tt> option:
file = 'black-flowers.m4a'
OSSObject.store(
file,
open(file),
'jukebox',
:content_type => 'audio/mp4a-latm'
)
You can read more about storing files on OSS in the documentation for OSSObject.store.
If you just want to fetch an object you've stored on OSS, you just specify its name and its bucket:
picture = OSSObject.find 'headshot.jpg', 'photos'
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.
You get the data for the file like this:
picture.value
You can fetch just the object's data directly:
OSSObject.value 'headshot.jpg', 'photos'
Or stream it by passing a block to <tt>stream</tt>:
open('song.mp3', 'w') do |file|
OSSObject.stream('song.mp3', 'jukebox') do |chunk|
file.write chunk
end
end
The data of the file, once download, is cached, so subsequent calls to <tt>value</tt> won't redownload the file unless you
tell the object to reload its <tt>value</tt>:
# Redownloads the file's data
song.value(:reload)
Other functionality includes:
# Check if an object exists?
OSSObject.exists? 'headshot.jpg', 'photos'
# Copying an object
OSSObject.copy 'headshot.jpg', 'headshot2.jpg', 'photos'
# Renaming an object
OSSObject.rename 'headshot.jpg', 'portrait.jpg', 'photos'
# Deleting an object
OSSObject.delete 'headshot.jpg', 'photos'
==== More about objects and their metadata
You can find out the content type of your object with the <tt>content_type</tt> method:
song.content_type
# => "audio/mpeg"
You can change the content type as well if you like:
song.content_type = 'application/pdf'
song.store
(Keep in mind that due to limitiations in OSS's exposed API, the only way to change things like the content_type
is to PUT the object onto OSS again. In the case of large files, this will result in fully re-uploading the file.)
A bevie of information about an object can be had using the <tt>about</tt> method:
pp song.about
{"last-modified" => "Sat, 28 Oct 2006 21:29:26 GMT",
"content-type" => "binary/octet-stream",
"etag" => "\"dc629038ffc674bee6f62eb64ff3a\"",
"date" => "Sat, 28 Oct 2006 21:30:41 GMT",
"x-amz-request-id" => "B7BC68F55495B1C8",
"server" => "AliyunOSS",
"content-length" => "3418766"}
You can get and set metadata for an object:
song.metadata
# => {}
song.metadata[:album] = "A River Ain't Too Much To Love"
# => "A River Ain't Too Much To Love"
song.metadata[:released] = 2005
pp song.metadata
{"x-amz-meta-released" => 2005,
"x-amz-meta-album" => "A River Ain't Too Much To Love"}
song.store
That metadata will be saved in OSS and is hence forth available from that object:
song = OSSObject.find('black-flowers.mp3', 'jukebox')
pp song.metadata
{"x-amz-meta-released" => "2005",
"x-amz-meta-album" => "A River Ain't Too Much To Love"}
song.metadata[:released]
# => "2005"
song.metadata[:released] = 2006
pp song.metadata
{"x-amz-meta-released" => 2006,
"x-amz-meta-album" => "A River Ain't Too Much To Love"}
==== Streaming uploads
When storing an object on the OSS servers using OSSObject.store, the <tt>data</tt> argument can be a string or an I/O stream.
If <tt>data</tt> is an I/O stream it will be read in segments and written to the socket incrementally. This approach
may be desirable for very large files so they are not read into memory all at once.
# Non streamed upload
OSSObject.store('greeting.txt', 'hello world!', 'marcel')
# Streamed upload
OSSObject.store('roots.mpeg', open('roots.mpeg'), 'marcel')
== Setting the current bucket
==== Scoping operations to a specific bucket
If you plan on always using a specific bucket for certain files, you can skip always having to specify the bucket by creating
a subclass of Bucket or OSSObject and telling it what bucket to use:
class JukeBoxSong < Aliyun::OSS::OSSObject
set_current_bucket_to 'jukebox'
end
For all methods that take a bucket name as an argument, the current bucket will be used if the bucket name argument is omitted.
other_song = 'baby-please-come-home.mp3'
JukeBoxSong.store(other_song, open(other_song))
This time we didn't have to explicitly pass in the bucket name, as the JukeBoxSong class knows that it will
always use the 'jukebox' bucket.
"Astute readers", as they say, may have noticed that we used the third parameter to pass in the content type,
rather than the fourth parameter as we had the last time we created an object. If the bucket can be inferred, or
is explicitly set, as we've done in the JukeBoxSong class, then the third argument can be used to pass in
options.
Now all operations that would have required a bucket name no longer do.
other_song = JukeBoxSong.find('baby-please-come-home.mp3')
== Access control
==== Using canned access control policies
By default buckets are private. This means that only the owner has access rights to the bucket and its objects.
Objects in that bucket inherit the permission of the bucket unless otherwise specified. When an object is private, the owner can
generate a signed url that exposes the object to anyone who has that url. Alternatively, buckets and objects can be given other
access levels. Several canned access levels are defined:
* <tt>:private</tt> - Owner gets FULL_CONTROL. No one else has any access rights. This is the default.
* <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.
* <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.
* <tt>:authenticated_read</tt> - Owner gets FULL_CONTROL, and any principal authenticated as a registered Aliyun OSS user is granted READ access.
You can set a canned access level when you create a bucket or an object by using the <tt>:access</tt> option:
OSSObject.store(
'kiss.jpg',
data,
'marcel',
:access => :public_read
)
Since the image we created is publicly readable, we can access it directly from a browser by going to the corresponding bucket name
and specifying the object's key without a special authenticated url:
http://oss.aliyuncs.com/marcel/kiss.jpg
==== Accessing private objects from a browser
All private objects are accessible via an authenticated GET request to the OSS servers. You can generate an
authenticated url for an object like this:
OSSObject.url_for('beluga_baby.jpg', 'marcel_molina')
By default authenticated urls expire 5 minutes after they were generated.
Expiration options can be specified either with an absolute time since the epoch with the <tt>:expires</tt> options,
or with a number of seconds relative to now with the <tt>:expires_in</tt> options:
# Absolute expiration date
# (Expires January 18th, 2038)
doomsday = Time.mktime(2038, 1, 18).to_i
OSSObject.url_for('beluga_baby.jpg',
'marcel',
:expires => doomsday)
# Expiration relative to now specified in seconds
# (Expires in 3 hours)
OSSObject.url_for('beluga_baby.jpg',
'marcel',
:expires_in => 60 * 60 * 3)
You can specify whether the url should go over SSL with the <tt>:use_ssl</tt> option:
# Url will use https protocol
OSSObject.url_for('beluga_baby.jpg',
'marcel',
:use_ssl => true)
By default, the ssl settings for the current connection will be used.
If you have an object handy, you can use its <tt>url</tt> method with the same objects:
song.url(:expires_in => 30)
To get an unauthenticated url for the object, such as in the case
when the object is publicly readable, pass the
<tt>:authenticated</tt> option with a value of <tt>false</tt>.
OSSObject.url_for('beluga_baby.jpg',
'marcel',
:authenticated => false)
# => http://oss.aliyuncs.com/marcel/beluga_baby.jpg
== Logging
==== Tracking requests made on a bucket
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:
Bucket.logging_enabled_for? 'jukebox'
# => false
Enabling it is easy:
Bucket.enable_logging_for('jukebox')
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:
Bucket.enable_logging_for(
'jukebox', 'target_bucket' => 'jukebox-logs'
)
Now instead of logging right into the jukebox bucket, the logs will go into the bucket called jukebox-logs.
Once logs have accumulated, you can access them using the <tt>logs</tt> method:
pp Bucket.logs('jukebox')
[#<Aliyun::OSS::Logging::Log '/jukebox-logs/log-2006-11-14-07-15-24-2061C35880A310A1'>,
#<Aliyun::OSS::Logging::Log '/jukebox-logs/log-2006-11-14-08-15-27-D8EEF536EC09E6B3'>,
#<Aliyun::OSS::Logging::Log '/jukebox-logs/log-2006-11-14-08-15-29-355812B2B15BD789'>]
Each log has a <tt>lines</tt> method that gives you information about each request in that log. All the fields are available
as named methods. More information is available in Logging::Log::Line.
logs = Bucket.logs('jukebox')
log = logs.first
line = log.lines.first
line.operation
# => 'REST.GET.LOGGING_STATUS'
line.request_uri
# => 'GET /jukebox?logging HTTP/1.1'
line.remote_ip
# => "67.165.183.125"
Disabling logging is just as simple as enabling it:
Bucket.disable_logging_for('jukebox')
== Errors
==== When things go wrong
Anything you do that makes a request to OSS could result in an error. If it does, the Aliyun::OSS library will raise an exception
specific to the error. All exception that are raised as a result of a request returning an error response inherit from the
ResponseError exception. So should you choose to rescue any such exception, you can simple rescue ResponseError.
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
errors listed at http://docs.aliyunwebservices.com/AliyunOSS/2006-03-01/ErrorCodeList.html):
begin
Bucket.delete('jukebox')
rescue ResponseError => error
# ...
end
Once you've captured the exception, you can extract the error message from OSS, as well as the full error response, which includes
things like the HTTP response code:
error
# => #<Aliyun::OSS::BucketNotEmpty The bucket you tried to delete is not empty>
error.message
# => "The bucket you tried to delete is not empty"
error.response.code
# => 409
You could use this information to redisplay the error in a way you see fit, or just to log the error and continue on.
==== Accessing the last request's response
Sometimes methods that make requests to the OSS servers return some object, like a Bucket or an OSSObject.
Othertimes they return just <tt>true</tt>. Other times they raise an exception that you may want to rescue. Despite all these
possible outcomes, every method that makes a request stores its response object for you in Service.response. You can always
get to the last request's response via Service.response.
objects = Bucket.objects('jukebox')
Service.response.success?
# => true
This is also useful when an error exception is raised in the console which you weren't expecting. You can
root around in the response to get more details of what might have gone wrong.