cmeiklejohn-aws 2.3.8

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,445 @@
1
+ #
2
+ # Copyright (c) 2007-2008 RightScale Inc
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ #
23
+
24
+ module Aws
25
+
26
+ #
27
+ # Right::Aws::SqsInterface - RightScale's low-level Amazon SQS interface
28
+ # for API version 2008-01-01 and later.
29
+ # For explanations of the semantics
30
+ # of each call, please refer to Amazon's documentation at
31
+ # http://developer.amazonwebservices.com/connect/kbcategory.jspa?categoryID=31
32
+ #
33
+ # This class provides a procedural interface to SQS. Conceptually it is
34
+ # mostly a pass-through interface to SQS and its API is very similar to the
35
+ # bare SQS API. For a somewhat higher-level and object-oriented interface, see
36
+ # Aws::Sqs.
37
+
38
+ class SqsInterface < AwsBase
39
+ include AwsBaseInterface
40
+
41
+ API_VERSION = "2009-02-01"
42
+ DEFAULT_HOST = "queue.amazonaws.com"
43
+ DEFAULT_PORT = 443
44
+ DEFAULT_PROTOCOL = 'https'
45
+ REQUEST_TTL = 30
46
+ DEFAULT_VISIBILITY_TIMEOUT = 30
47
+
48
+
49
+ @@bench = AwsBenchmarkingBlock.new
50
+ def self.bench_xml
51
+ @@bench.xml
52
+ end
53
+ def self.bench_sqs
54
+ @@bench.service
55
+ end
56
+
57
+ @@api = API_VERSION
58
+ def self.api
59
+ @@api
60
+ end
61
+
62
+ # Creates a new SqsInterface instance. This instance is limited to
63
+ # operations on SQS objects created with Amazon's 2008-01-01 API version. This
64
+ # interface will not work on objects created with prior API versions. See
65
+ # Amazon's article "Migrating to Amazon SQS API version 2008-01-01" at:
66
+ # http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1148
67
+ #
68
+ # sqs = Aws::SqsInterface.new('1E3GDYEOGFJPIT75KDT40','hgTHt68JY07JKUY08ftHYtERkjgtfERn57DFE379', {:multi_thread => true, :logger => Logger.new('/tmp/x.log')})
69
+ #
70
+ # Params is a hash:
71
+ #
72
+ # {:server => 'queue.amazonaws.com' # Amazon service host: 'queue.amazonaws.com' (default)
73
+ # :port => 443 # Amazon service port: 80 or 443 (default)
74
+ # :multi_thread => true|false # Multi-threaded (connection per each thread): true or false (default)
75
+ # :signature_version => '0' # The signature version : '0' or '1'(default)
76
+ # :logger => Logger Object} # Logger instance: logs to STDOUT if omitted }
77
+ #
78
+ def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
79
+ init({ :name => 'SQS',
80
+ :default_host => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).host : DEFAULT_HOST,
81
+ :default_port => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).port : DEFAULT_PORT,
82
+ :default_protocol => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).scheme : DEFAULT_PROTOCOL,
83
+ :api_version => API_VERSION },
84
+ aws_access_key_id || ENV['AWS_ACCESS_KEY_ID'],
85
+ aws_secret_access_key || ENV['AWS_SECRET_ACCESS_KEY'],
86
+ params)
87
+ end
88
+
89
+
90
+ #-----------------------------------------------------------------
91
+ # Requests
92
+ #-----------------------------------------------------------------
93
+
94
+ # Generates a request hash for the query API
95
+ def generate_request(action, param={}) # :nodoc:
96
+ # For operation requests on a queue, the queue URI will be a parameter,
97
+ # so we first extract it from the call parameters. Next we remove any
98
+ # parameters with no value or with symbolic keys. We add the header
99
+ # fields required in all requests, and then the headers passed in as
100
+ # params. We sort the header fields alphabetically and then generate the
101
+ # signature before URL escaping the resulting query and sending it.
102
+ service = param[:queue_url] ? URI(param[:queue_url]).path : '/'
103
+ param.each{ |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
104
+ service_hash = { "Action" => action,
105
+ "Expires" => (Time.now + REQUEST_TTL).utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
106
+ "AWSAccessKeyId" => @aws_access_key_id,
107
+ "Version" => API_VERSION }
108
+ service_hash.update(param)
109
+ service_params = signed_service_params(@aws_secret_access_key, service_hash, :get, @params[:server], service)
110
+ request = Net::HTTP::Get.new("#{AwsUtils.URLencode(service)}?#{service_params}")
111
+ # prepare output hash
112
+ { :request => request,
113
+ :server => @params[:server],
114
+ :port => @params[:port],
115
+ :protocol => @params[:protocol] }
116
+ end
117
+
118
+ def generate_post_request(action, param={}) # :nodoc:
119
+ service = param[:queue_url] ? URI(param[:queue_url]).path : '/'
120
+ message = param[:message] # extract message body if nesessary
121
+ param.each{ |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
122
+ service_hash = { "Action" => action,
123
+ "Expires" => (Time.now + REQUEST_TTL).utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
124
+ "AWSAccessKeyId" => @aws_access_key_id,
125
+ "MessageBody" => message,
126
+ "Version" => API_VERSION }
127
+ service_hash.update(param)
128
+ #
129
+ service_params = signed_service_params(@aws_secret_access_key, service_hash, :post, @params[:server], service)
130
+ request = Net::HTTP::Post.new(AwsUtils::URLencode(service))
131
+ request['Content-Type'] = 'application/x-www-form-urlencoded'
132
+ request.body = service_params
133
+ # prepare output hash
134
+ { :request => request,
135
+ :server => @params[:server],
136
+ :port => @params[:port],
137
+ :protocol => @params[:protocol] }
138
+ end
139
+
140
+
141
+ # Sends request to Amazon and parses the response
142
+ # Raises AwsError if any banana happened
143
+ def request_info(request, parser) # :nodoc:
144
+ thread = @params[:multi_thread] ? Thread.current : Thread.main
145
+ thread[:sqs_connection] ||= Rightscale::HttpConnection.new(:exception => AwsError, :logger => @logger)
146
+ request_info_impl(thread[:sqs_connection], @@bench, request, parser)
147
+ end
148
+
149
+
150
+ # Creates a new queue, returning its URI.
151
+ #
152
+ # sqs.create_queue('my_awesome_queue') #=> 'http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
153
+ #
154
+ def create_queue(queue_name, default_visibility_timeout=nil)
155
+ req_hash = generate_request('CreateQueue', 'QueueName' => queue_name,
156
+ 'DefaultVisibilityTimeout' => default_visibility_timeout || DEFAULT_VISIBILITY_TIMEOUT )
157
+ request_info(req_hash, SqsCreateQueueParser.new(:logger => @logger))
158
+ rescue
159
+ on_exception
160
+ end
161
+
162
+ # Lists all queues owned by this user that have names beginning with +queue_name_prefix+.
163
+ # If +queue_name_prefix+ is omitted then retrieves a list of all queues.
164
+ # Queue creation is an eventual operation and created queues may not show up in immediately subsequent list_queues calls.
165
+ #
166
+ # sqs.create_queue('my_awesome_queue')
167
+ # sqs.create_queue('my_awesome_queue_2')
168
+ # sqs.list_queues('my_awesome') #=> ['http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue','http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2']
169
+ #
170
+ def list_queues(queue_name_prefix=nil)
171
+ req_hash = generate_request('ListQueues', 'QueueNamePrefix' => queue_name_prefix)
172
+ request_info(req_hash, SqsListQueuesParser.new(:logger => @logger))
173
+ rescue
174
+ on_exception
175
+ end
176
+
177
+ # Deletes queue. Any messages in the queue are permanently lost.
178
+ # Returns +true+ or an exception.
179
+ # Queue deletion can take up to 60 s to propagate through SQS. Thus, after a deletion, subsequent list_queues calls
180
+ # may still show the deleted queue. It is not unusual within the 60 s window to see the deleted queue absent from
181
+ # one list_queues call but present in the subsequent one. Deletion is eventual.
182
+ #
183
+ # sqs.delete_queue('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2') #=> true
184
+ #
185
+ #
186
+ def delete_queue(queue_url)
187
+ req_hash = generate_request('DeleteQueue', :queue_url => queue_url)
188
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
189
+ rescue
190
+ on_exception
191
+ end
192
+
193
+ # Retrieves the queue attribute(s). Returns a hash of attribute(s) or an exception.
194
+ #
195
+ # sqs.get_queue_attributes('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue')
196
+ # #=> {"ApproximateNumberOfMessages"=>"0", "VisibilityTimeout"=>"30"}
197
+ #
198
+ def get_queue_attributes(queue_url, attribute='All')
199
+ req_hash = generate_request('GetQueueAttributes', 'AttributeName' => attribute, :queue_url => queue_url)
200
+ request_info(req_hash, SqsGetQueueAttributesParser.new(:logger => @logger))
201
+ rescue
202
+ on_exception
203
+ end
204
+
205
+ # Sets queue attribute. Returns +true+ or an exception.
206
+ #
207
+ # sqs.set_queue_attributes('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', "VisibilityTimeout", 10) #=> true
208
+ #
209
+ # From the SQS Dev Guide:
210
+ # "Currently, you can set only the
211
+ # VisibilityTimeout attribute for a queue...
212
+ # When you change a queue's attributes, the change can take up to 60 seconds to propagate
213
+ # throughout the SQS system."
214
+ #
215
+ # NB: Attribute values may not be immediately available to other queries
216
+ # for some time after an update. See the SQS documentation for
217
+ # semantics, but in general propagation can take up to 60 s.
218
+ def set_queue_attributes(queue_url, attribute, value)
219
+ req_hash = generate_request('SetQueueAttributes', 'Attribute.Name' => attribute, 'Attribute.Value' => value, :queue_url => queue_url)
220
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
221
+ rescue
222
+ on_exception
223
+ end
224
+
225
+ # Retrieves a list of messages from queue. Returns an array of hashes in format: <tt>{:id=>'message_id', body=>'message_body'}</tt>
226
+ #
227
+ # sqs.receive_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',10, 5) #=>
228
+ # [{"ReceiptHandle"=>"Euvo62...kw==", "MD5OfBody"=>"16af2171b5b83cfa35ce254966ba81e3",
229
+ # "Body"=>"Goodbyte World!", "MessageId"=>"MUM4WlAyR...pYOTA="}, ..., {}]
230
+ #
231
+ # Normally this call returns fewer messages than the maximum specified,
232
+ # even if they are available.
233
+ #
234
+ def receive_message(queue_url, max_number_of_messages=1, visibility_timeout=nil)
235
+ return [] if max_number_of_messages == 0
236
+ req_hash = generate_post_request('ReceiveMessage', 'MaxNumberOfMessages' => max_number_of_messages, 'VisibilityTimeout' => visibility_timeout,
237
+ :queue_url => queue_url )
238
+ request_info(req_hash, SqsReceiveMessageParser.new(:logger => @logger))
239
+ rescue
240
+ on_exception
241
+ end
242
+
243
+ # Sends a new message to a queue. Message size is limited to 8 KB.
244
+ # If successful, this call returns a hash containing key/value pairs for
245
+ # "MessageId" and "MD5OfMessageBody":
246
+ #
247
+ # sqs.send_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'message_1') #=> "1234567890...0987654321"
248
+ # => {"MessageId"=>"MEs4M0JKNlRCRTBBSENaMjROTk58QVFRNzNEREhDVFlFOVJDQ1JKNjF8UTdBRllCUlJUMjhKMUI1WDJSWDE=", "MD5OfMessageBody"=>"16af2171b5b83cfa35ce254966ba81e3"}
249
+ #
250
+ # On failure, send_message raises an exception.
251
+ #
252
+ #
253
+ def send_message(queue_url, message)
254
+ req_hash = generate_post_request('SendMessage', :message => message, :queue_url => queue_url)
255
+ request_info(req_hash, SqsSendMessagesParser.new(:logger => @logger))
256
+ rescue
257
+ on_exception
258
+ end
259
+
260
+ # Same as send_message
261
+ alias_method :push_message, :send_message
262
+
263
+
264
+ # Deletes message from queue. Returns +true+ or an exception. Amazon
265
+ # returns +true+ on deletion of non-existent messages. You must use the
266
+ # receipt handle for a message to delete it, not the message ID.
267
+ #
268
+ # From the SQS Developer Guide:
269
+ # "It is possible you will receive a message even after you have deleted it. This might happen
270
+ # on rare occasions if one of the servers storing a copy of the message is unavailable when
271
+ # you request to delete the message. The copy remains on the server and might be returned to
272
+ # you again on a subsequent receive request. You should create your system to be
273
+ # idempotent so that receiving a particular message more than once is not a problem. "
274
+ #
275
+ # sqs.delete_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'Euvo62/1nlIet...ao03hd9Sa0w==') #=> true
276
+ #
277
+ def delete_message(queue_url, receipt_handle)
278
+ req_hash = generate_request('DeleteMessage', 'ReceiptHandle' => receipt_handle, :queue_url => queue_url)
279
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
280
+ rescue
281
+ on_exception
282
+ end
283
+
284
+ # Given the queue's short name, this call returns the queue URL or +nil+ if queue is not found
285
+ # sqs.queue_url_by_name('my_awesome_queue') #=> 'http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
286
+ #
287
+ def queue_url_by_name(queue_name)
288
+ return queue_name if queue_name.include?('/')
289
+ queue_urls = list_queues(queue_name)
290
+ queue_urls.each do |queue_url|
291
+ return queue_url if queue_name_by_url(queue_url) == queue_name
292
+ end
293
+ nil
294
+ rescue
295
+ on_exception
296
+ end
297
+
298
+ # Returns short queue name by url.
299
+ #
300
+ # RightSqs.queue_name_by_url('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
301
+ #
302
+ def self.queue_name_by_url(queue_url)
303
+ queue_url[/[^\/]*$/]
304
+ rescue
305
+ on_exception
306
+ end
307
+
308
+ # Returns short queue name by url.
309
+ #
310
+ # sqs.queue_name_by_url('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
311
+ #
312
+ def queue_name_by_url(queue_url)
313
+ self.class.queue_name_by_url(queue_url)
314
+ rescue
315
+ on_exception
316
+ end
317
+
318
+ # Returns approximate number of messages in queue.
319
+ #
320
+ # sqs.get_queue_length('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 3
321
+ #
322
+ def get_queue_length(queue_url)
323
+ get_queue_attributes(queue_url)['ApproximateNumberOfMessages'].to_i
324
+ rescue
325
+ on_exception
326
+ end
327
+
328
+ # Removes all visible messages from queue. Return +true+ or an exception.
329
+ #
330
+ # sqs.clear_queue('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> true
331
+ #
332
+ def clear_queue(queue_url)
333
+ while (pop_messages(queue_url, 10).length > 0) ; end # delete all messages in queue
334
+ true
335
+ rescue
336
+ on_exception
337
+ end
338
+
339
+ # Pops (retrieves and deletes) up to 'number_of_messages' from queue. Returns an array of retrieved messages in format: <tt>[{:id=>'message_id', :body=>'message_body'}]</tt>.
340
+ #
341
+ # sqs.pop_messages('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 3) #=>
342
+ # [{"ReceiptHandle"=>"Euvo62/...+Zw==", "MD5OfBody"=>"16af2...81e3", "Body"=>"Goodbyte World!",
343
+ # "MessageId"=>"MEZI...JSWDE="}, {...}, ... , {...} ]
344
+ #
345
+ def pop_messages(queue_url, number_of_messages=1)
346
+ messages = receive_message(queue_url, number_of_messages)
347
+ messages.each do |message|
348
+ delete_message(queue_url, message['ReceiptHandle'])
349
+ end
350
+ messages
351
+ rescue
352
+ on_exception
353
+ end
354
+
355
+ # Pops (retrieves and deletes) first accessible message from queue. Returns the message in format <tt>{:id=>'message_id', :body=>'message_body'}</tt> or +nil+.
356
+ #
357
+ # sqs.pop_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=>
358
+ # {:id=>"12345678904GEZX9746N|0N9ED344VK5Z3SV1DTM0|1RVYH4X3TJ0987654321", :body=>"message_1"}
359
+ #
360
+ def pop_message(queue_url)
361
+ messages = pop_messages(queue_url)
362
+ messages.blank? ? nil : messages[0]
363
+ rescue
364
+ on_exception
365
+ end
366
+
367
+ #-----------------------------------------------------------------
368
+ # PARSERS: Status Response Parser
369
+ #-----------------------------------------------------------------
370
+
371
+ class SqsStatusParser < AwsParser # :nodoc:
372
+ def tagend(name)
373
+ if name == 'ResponseMetadata'
374
+ @result = true
375
+ end
376
+ end
377
+ end
378
+
379
+ #-----------------------------------------------------------------
380
+ # PARSERS: Queue
381
+ #-----------------------------------------------------------------
382
+
383
+ class SqsCreateQueueParser < AwsParser # :nodoc:
384
+ def tagend(name)
385
+ @result = @text if name == 'QueueUrl'
386
+ end
387
+ end
388
+
389
+ class SqsListQueuesParser < AwsParser # :nodoc:
390
+ def reset
391
+ @result = []
392
+ end
393
+ def tagend(name)
394
+ @result << @text if name == 'QueueUrl'
395
+ end
396
+ end
397
+
398
+ class SqsGetQueueAttributesParser < AwsParser # :nodoc:
399
+ def reset
400
+ @result = {}
401
+ end
402
+ def tagend(name)
403
+ case name
404
+ when 'Name' ; @current_attribute = @text
405
+ when 'Value' ; @result[@current_attribute] = @text
406
+ end
407
+ end
408
+ end
409
+
410
+ #-----------------------------------------------------------------
411
+ # PARSERS: Messages
412
+ #-----------------------------------------------------------------
413
+
414
+ class SqsReceiveMessageParser < AwsParser # :nodoc:
415
+ def reset
416
+ @result = []
417
+ end
418
+ def tagstart(name, attributes)
419
+ @current_message = {} if name == 'Message'
420
+ end
421
+ def tagend(name)
422
+ case name
423
+ when 'MessageId' ; @current_message['MessageId'] = @text
424
+ when 'ReceiptHandle' ; @current_message['ReceiptHandle'] = @text
425
+ when 'MD5OfBody' ; @current_message['MD5OfBody'] = @text
426
+ when 'Body'; @current_message['Body'] = @text; @result << @current_message
427
+ end
428
+ end
429
+ end
430
+
431
+ class SqsSendMessagesParser < AwsParser # :nodoc:
432
+ def reset
433
+ @result = {}
434
+ end
435
+ def tagend(name)
436
+ case name
437
+ when 'MessageId' ; @result['MessageId'] = @text
438
+ when 'MD5OfMessageBody' ; @result['MD5OfMessageBody'] = @text
439
+ end
440
+ end
441
+ end
442
+
443
+ end
444
+
445
+ end
@@ -0,0 +1,148 @@
1
+ require File.dirname(__FILE__) + '/test_helper.rb'
2
+ require File.dirname(__FILE__) + '/../test_credentials.rb'
3
+
4
+ class TestAcf < Test::Unit::TestCase
5
+
6
+ RIGHT_OBJECT_TEXT = 'Right test message'
7
+
8
+ STDOUT.sync = true
9
+
10
+ def setup
11
+ TestCredentials.get_credentials
12
+ @acf= Aws::AcfInterface.new(TestCredentials.aws_access_key_id, TestCredentials.aws_secret_access_key)
13
+ @s3 = Aws::S3.new(TestCredentials.aws_access_key_id, TestCredentials.aws_secret_access_key)
14
+ @bucket_name = "right-acf-awesome-test-bucket-0001"
15
+ @bucket_domain = "#{@bucket_name}.s3.amazonaws.com"
16
+ end
17
+
18
+ def test_01_list_distributions_part1
19
+ distributions = nil
20
+ assert_nothing_raised(Aws::AwsError) do
21
+ distributions = @acf.list_distributions
22
+ end
23
+ assert distributions.is_a?(Array)
24
+ end
25
+
26
+ def test_02_try_to_create_for_bad_bucket
27
+ # a bucket does not exist
28
+ assert_raise(Aws::AwsError) do
29
+ @acf.create_distribution("right-cloudfront-awesome-test-bucket-not-exist", "Mustn't to be born", true)
30
+ end
31
+ # a bucket is not a domain naming complied guy
32
+ bucket_name = 'right_cloudfront_awesome_test_bucket_BAD'
33
+ @s3.bucket(bucket_name, :create)
34
+ assert_raise(Aws::AwsError) do
35
+ @acf.create_distribution(bucket_name, "Mustn't to be born", true)
36
+ end
37
+ end
38
+
39
+ def test_03_create
40
+ comment = 'WooHoo!!!'
41
+ # create a test bucket
42
+ @s3.bucket(@bucket_name, :create)
43
+ # create a distribution
44
+ distribution = @acf.create_distribution(@bucket_domain, comment, true)
45
+ assert_equal comment, distribution[:comment]
46
+ assert distribution[:cnames].size == 0
47
+ assert distribution[:enabled]
48
+ end
49
+
50
+ def test_04_list_distributions_part2
51
+ distributions = @acf.list_distributions
52
+ assert distributions.size > 0
53
+ end
54
+
55
+ def get_test_distribution
56
+ @acf.list_distributions.select{ |d| d[:origin] == @bucket_domain }.first
57
+ end
58
+
59
+ def test_05_get_distribution
60
+ old = get_test_distribution
61
+ assert_nothing_raised do
62
+ @acf.get_distribution(old[:aws_id])
63
+ end
64
+ end
65
+
66
+ def test_06_get_and_set_config
67
+ config = nil
68
+ old = get_test_distribution
69
+ assert_nothing_raised do
70
+ config = @acf.get_distribution_config(old[:aws_id])
71
+ end
72
+ # change a config
73
+ config[:enabled] = false
74
+ config[:cnames] << 'x1.myawesomesite.com'
75
+ config[:cnames] << 'x2.myawesomesite.com'
76
+ # set config
77
+ set_config_result = nil
78
+ assert_nothing_raised do
79
+ set_config_result = @acf.set_distribution_config(old[:aws_id], config)
80
+ end
81
+ assert set_config_result
82
+ # reget the config and check
83
+ new_config = nil
84
+ assert_nothing_raised do
85
+ new_config = @acf.get_distribution_config(old[:aws_id])
86
+ end
87
+ assert !new_config[:enabled]
88
+ assert_equal new_config[:cnames].sort, ['x1.myawesomesite.com', 'x2.myawesomesite.com']
89
+ assert_not_equal config[:e_tag], new_config[:e_tag]
90
+
91
+ # try to update the old config again (must fail because ETAG has changed)
92
+ assert_raise(Aws::AwsError) do
93
+ @acf.set_distribution_config(old[:aws_id], config)
94
+ end
95
+ end
96
+
97
+ def test_07_caching
98
+ # enable caching
99
+ @acf.params[:cache] = true
100
+ # list distributions
101
+ @acf.list_distributions
102
+ # list the distributions again - cache should hit
103
+ assert_raise(Aws::AwsNoChange) do
104
+ @acf.list_distributions
105
+ end
106
+ # disable caching
107
+ @acf.params[:cache] = true
108
+ end
109
+
110
+ def test_08_delete_distribution
111
+ # we need ETAG so use get_distribution
112
+ distribution = @acf.get_distribution(get_test_distribution[:aws_id])
113
+ # try to delete a distribution
114
+ # should fail because
115
+ if distribution[:status] == 'InProgress'
116
+ # should fail because the distribution is not deployed yet
117
+ assert_raise(Aws::AwsError) do
118
+ @acf.delete_distribution(distribution[:aws_id], distribution[:e_tag])
119
+ end
120
+ # wait for a deployed state
121
+ print "waiting up to 5 min while the distribution is being deployed: "
122
+ 100.times do
123
+ print '.'
124
+ distribution = @acf.get_distribution(distribution[:aws_id])
125
+ if distribution[:status] == 'Deployed'
126
+ print ' done'
127
+ break
128
+ end
129
+ sleep 3
130
+ end
131
+ puts
132
+ end
133
+
134
+ # only disabled and deployed distribution can be deleted
135
+ assert_equal 'Deployed', distribution[:status]
136
+ assert !distribution[:enabled]
137
+
138
+ # delete the distribution
139
+ assert_nothing_raised do
140
+ @acf.delete_distribution(distribution[:aws_id], distribution[:e_tag])
141
+ end
142
+ end
143
+
144
+ def test_09_drop_bucket
145
+ assert @s3.bucket(@bucket_name).delete
146
+ end
147
+
148
+ end
@@ -0,0 +1,2 @@
1
+ require 'test/unit'
2
+ require File.dirname(__FILE__) + '/../../lib/right_aws'