revans_right_aws 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. data/.gemtest +0 -0
  2. data/History.txt +284 -0
  3. data/Manifest.txt +50 -0
  4. data/README.txt +167 -0
  5. data/Rakefile +110 -0
  6. data/lib/acf/right_acf_interface.rb +485 -0
  7. data/lib/acf/right_acf_origin_access_identities.rb +230 -0
  8. data/lib/acf/right_acf_streaming_interface.rb +236 -0
  9. data/lib/acw/right_acw_interface.rb +249 -0
  10. data/lib/as/right_as_interface.rb +699 -0
  11. data/lib/awsbase/benchmark_fix.rb +39 -0
  12. data/lib/awsbase/right_awsbase.rb +978 -0
  13. data/lib/awsbase/support.rb +115 -0
  14. data/lib/ec2/right_ec2.rb +395 -0
  15. data/lib/ec2/right_ec2_ebs.rb +452 -0
  16. data/lib/ec2/right_ec2_images.rb +373 -0
  17. data/lib/ec2/right_ec2_instances.rb +755 -0
  18. data/lib/ec2/right_ec2_monitoring.rb +70 -0
  19. data/lib/ec2/right_ec2_reserved_instances.rb +170 -0
  20. data/lib/ec2/right_ec2_security_groups.rb +277 -0
  21. data/lib/ec2/right_ec2_spot_instances.rb +399 -0
  22. data/lib/ec2/right_ec2_vpc.rb +571 -0
  23. data/lib/elb/right_elb_interface.rb +496 -0
  24. data/lib/rds/right_rds_interface.rb +998 -0
  25. data/lib/right_aws.rb +83 -0
  26. data/lib/s3/right_s3.rb +1126 -0
  27. data/lib/s3/right_s3_interface.rb +1199 -0
  28. data/lib/sdb/active_sdb.rb +1122 -0
  29. data/lib/sdb/right_sdb_interface.rb +721 -0
  30. data/lib/sqs/right_sqs.rb +388 -0
  31. data/lib/sqs/right_sqs_gen2.rb +343 -0
  32. data/lib/sqs/right_sqs_gen2_interface.rb +524 -0
  33. data/lib/sqs/right_sqs_interface.rb +594 -0
  34. data/test/acf/test_helper.rb +2 -0
  35. data/test/acf/test_right_acf.rb +138 -0
  36. data/test/ec2/test_helper.rb +2 -0
  37. data/test/ec2/test_right_ec2.rb +108 -0
  38. data/test/http_connection.rb +87 -0
  39. data/test/rds/test_helper.rb +2 -0
  40. data/test/rds/test_right_rds.rb +120 -0
  41. data/test/s3/test_helper.rb +2 -0
  42. data/test/s3/test_right_s3.rb +421 -0
  43. data/test/s3/test_right_s3_stubbed.rb +97 -0
  44. data/test/sdb/test_active_sdb.rb +357 -0
  45. data/test/sdb/test_helper.rb +3 -0
  46. data/test/sdb/test_right_sdb.rb +253 -0
  47. data/test/sqs/test_helper.rb +2 -0
  48. data/test/sqs/test_right_sqs.rb +291 -0
  49. data/test/sqs/test_right_sqs_gen2.rb +264 -0
  50. data/test/test_credentials.rb +37 -0
  51. data/test/ts_right_aws.rb +14 -0
  52. metadata +169 -0
@@ -0,0 +1,524 @@
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 RightAws
25
+
26
+ #
27
+ # Right::Aws::SqsGen2Interface - 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
+ # RightAws::SqsGen2.
37
+
38
+ class SqsGen2Interface < RightAwsBase
39
+ include RightAwsBaseInterface
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 = RightAws::SqsGen2Interface.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', '1' or '2'(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
+ aws_access_key_id || ENV['AWS_ACCESS_KEY_ID'],
84
+ aws_secret_access_key || ENV['AWS_SECRET_ACCESS_KEY'],
85
+ params)
86
+ end
87
+
88
+
89
+ #-----------------------------------------------------------------
90
+ # Requests
91
+ #-----------------------------------------------------------------
92
+
93
+ # Generates a request hash for the query API
94
+ def generate_request(action, param={}) # :nodoc:
95
+ # For operation requests on a queue, the queue URI will be a parameter,
96
+ # so we first extract it from the call parameters. Next we remove any
97
+ # parameters with no value or with symbolic keys. We add the header
98
+ # fields required in all requests, and then the headers passed in as
99
+ # params. We sort the header fields alphabetically and then generate the
100
+ # signature before URL escaping the resulting query and sending it.
101
+ service = param[:queue_url] ? URI(param[:queue_url]).path : '/'
102
+ param.each{ |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
103
+ service_hash = { "Action" => action,
104
+ "Expires" => (Time.now + REQUEST_TTL).utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
105
+ "AWSAccessKeyId" => @aws_access_key_id,
106
+ "Version" => API_VERSION }
107
+ service_hash.update(param)
108
+ service_params = signed_service_params(@aws_secret_access_key, service_hash, :get, @params[:server], service)
109
+ request = Net::HTTP::Get.new("#{AwsUtils.URLencode(service)}?#{service_params}")
110
+ # prepare output hash
111
+ { :request => request,
112
+ :server => @params[:server],
113
+ :port => @params[:port],
114
+ :protocol => @params[:protocol] }
115
+ end
116
+
117
+ def generate_post_request(action, param={}) # :nodoc:
118
+ service = param[:queue_url] ? URI(param[:queue_url]).path : '/'
119
+ message = param[:message] # extract message body if nesessary
120
+ param.each{ |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
121
+ service_hash = { "Action" => action,
122
+ "Expires" => (Time.now + REQUEST_TTL).utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
123
+ "AWSAccessKeyId" => @aws_access_key_id,
124
+ "MessageBody" => message,
125
+ "Version" => API_VERSION }
126
+ service_hash.update(param)
127
+ #
128
+ service_params = signed_service_params(@aws_secret_access_key, service_hash, :post, @params[:server], service)
129
+ request = Net::HTTP::Post.new(AwsUtils::URLencode(service))
130
+ request['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
131
+ request.body = service_params
132
+ # prepare output hash
133
+ { :request => request,
134
+ :server => @params[:server],
135
+ :port => @params[:port],
136
+ :protocol => @params[:protocol] }
137
+ end
138
+
139
+
140
+ # Sends request to Amazon and parses the response
141
+ # Raises AwsError if any banana happened
142
+ def request_info(request, parser) # :nodoc:
143
+ request_info_impl(:sqs_connection, @@bench, request, parser)
144
+ end
145
+
146
+ # Creates a new queue, returning its URI.
147
+ #
148
+ # sqs.create_queue('my_awesome_queue') #=> 'https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
149
+ #
150
+ def create_queue(queue_name, default_visibility_timeout=nil)
151
+ req_hash = generate_request('CreateQueue', 'QueueName' => queue_name,
152
+ 'DefaultVisibilityTimeout' => default_visibility_timeout || DEFAULT_VISIBILITY_TIMEOUT )
153
+ request_info(req_hash, SqsCreateQueueParser.new(:logger => @logger))
154
+ rescue
155
+ on_exception
156
+ end
157
+
158
+ # Lists all queues owned by this user that have names beginning with +queue_name_prefix+.
159
+ # If +queue_name_prefix+ is omitted then retrieves a list of all queues.
160
+ # Queue creation is an eventual operation and created queues may not show up in immediately subsequent list_queues calls.
161
+ #
162
+ # sqs.create_queue('my_awesome_queue')
163
+ # sqs.create_queue('my_awesome_queue_2')
164
+ # sqs.list_queues('my_awesome') #=> ['https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue','https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2']
165
+ #
166
+ def list_queues(queue_name_prefix=nil)
167
+ req_hash = generate_request('ListQueues', 'QueueNamePrefix' => queue_name_prefix)
168
+ request_info(req_hash, SqsListQueuesParser.new(:logger => @logger))
169
+ rescue
170
+ on_exception
171
+ end
172
+
173
+ # Deletes queue. Any messages in the queue are permanently lost.
174
+ # Returns +true+ or an exception.
175
+ # Queue deletion can take up to 60 s to propagate through SQS. Thus, after a deletion, subsequent list_queues calls
176
+ # may still show the deleted queue. It is not unusual within the 60 s window to see the deleted queue absent from
177
+ # one list_queues call but present in the subsequent one. Deletion is eventual.
178
+ #
179
+ # sqs.delete_queue('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2') #=> true
180
+ #
181
+ def delete_queue(queue_url)
182
+ req_hash = generate_request('DeleteQueue', :queue_url => queue_url)
183
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
184
+ rescue
185
+ on_exception
186
+ end
187
+
188
+ # Retrieves the queue attribute(s). Returns a hash of attribute(s) or an exception.
189
+ #
190
+ # sqs.get_queue_attributes('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=>
191
+ # {"ApproximateNumberOfMessages" => "0",
192
+ # "LastModifiedTimestamp" => "1240946032",
193
+ # "CreatedTimestamp" => "1240816887",
194
+ # "VisibilityTimeout" => "30",
195
+ # "Policy" => "{"Version":"2008-10-17","Id":...}"}
196
+ #
197
+ # queue.get_queue_attributes('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', "LastModifiedTimestamp", "VisibilityTimeout") #=>
198
+ # {"LastModifiedTimestamp" => "1240946032",
199
+ # "VisibilityTimeout" => "30"}
200
+ #
201
+ # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryGetQueueAttributes.html
202
+ def get_queue_attributes(queue_url, *attributes)
203
+ attributes.flatten!
204
+ attributes << 'All' if attributes.blank?
205
+ params = amazonize_list('AttributeName', attributes)
206
+ params.merge!(:queue_url => queue_url)
207
+ req_hash = generate_request('GetQueueAttributes', params)
208
+ request_info(req_hash, SqsGetQueueAttributesParser.new(:logger => @logger))
209
+ rescue
210
+ on_exception
211
+ end
212
+
213
+ # Sets queue attribute. Returns +true+ or an exception.
214
+ #
215
+ # sqs.set_queue_attributes('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', "VisibilityTimeout", 10) #=> true
216
+ #
217
+ # From the SQS Dev Guide:
218
+ # "When you change a queue's attributes, the change can take up to 60 seconds to propagate
219
+ # throughout the SQS system."
220
+ #
221
+ # NB: Attribute values may not be immediately available to other queries
222
+ # for some time after an update. See the SQS documentation for
223
+ # semantics, but in general propagation can take up to 60 s.
224
+ #
225
+ # see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QuerySetQueueAttributes.html
226
+ def set_queue_attributes(queue_url, attribute, value)
227
+ req_hash = generate_request('SetQueueAttributes',
228
+ 'Attribute.Name' => attribute,
229
+ 'Attribute.Value' => value,
230
+ :queue_url => queue_url)
231
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
232
+ rescue
233
+ on_exception
234
+ end
235
+
236
+ # Add permissions to a queue.
237
+ #
238
+ # sqs.add_permissions('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',
239
+ # 'testLabel', ['125074342641','125074342642'],
240
+ # ['SendMessage','SendMessage','ReceiveMessage']) #=> true
241
+ #
242
+ # +permissions+ is a hash of: AccountId => ActionName
243
+ # (valid ActionNames: * | SendMessage | ReceiveMessage | DeleteMessage | ChangeMessageVisibility | GetQueueAttributes )
244
+ #
245
+ # see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryAddPermission.html
246
+ # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?acp-overview.html
247
+ def add_permissions(queue_url, label, grantees, actions)
248
+ params = amazonize_list('AWSAccountId', Array(grantees))
249
+ params.merge!(amazonize_list('ActionName', Array(actions)))
250
+ params.merge!('Label' => label,
251
+ :queue_url => queue_url )
252
+ req_hash = generate_request('AddPermission', params)
253
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
254
+ rescue
255
+ on_exception
256
+ end
257
+
258
+ # Revoke any permissions in the queue policy that matches the +label+ parameter.
259
+ #
260
+ # sqs.remove_permissions('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',
261
+ # 'testLabel') # => true
262
+ #
263
+ # see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryRemovePermission.html
264
+ def remove_permissions(queue_url, label)
265
+ req_hash = generate_request('RemovePermission',
266
+ 'Label' => label,
267
+ :queue_url => queue_url )
268
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
269
+ rescue
270
+ on_exception
271
+ end
272
+
273
+ # Retrieves a list of messages from queue. Returns an array of hashes in format: <tt>{:id=>'message_id', :body=>'message_body'}</tt>
274
+ #
275
+ # sqs.receive_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',10, 5) #=>
276
+ # [{"ReceiptHandle"=>"Euvo62...kw==", "MD5OfBody"=>"16af2171b5b83cfa35ce254966ba81e3",
277
+ # "Body"=>"Goodbyte World!", "MessageId"=>"MUM4WlAyR...pYOTA="}, ..., {}]
278
+ #
279
+ # Normally this call returns fewer messages than the maximum specified,
280
+ # even if they are available.
281
+ #
282
+ def receive_message(queue_url, max_number_of_messages=1, visibility_timeout=nil, attributes=nil)
283
+ return [] if max_number_of_messages == 0
284
+ params = {}
285
+ params.merge!(amazonize_list('AttributeName', Array(attributes))) unless attributes.blank?
286
+ params.merge!('MaxNumberOfMessages' => max_number_of_messages,
287
+ 'VisibilityTimeout' => visibility_timeout,
288
+ :queue_url => queue_url )
289
+ req_hash = generate_post_request('ReceiveMessage', params)
290
+ request_info(req_hash, SqsReceiveMessageParser.new(:logger => @logger))
291
+ rescue
292
+ on_exception
293
+ end
294
+
295
+ # Change the visibility timeout of a specified message in a queue.
296
+ #
297
+ # sqs.change_message_visibility('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'Euvo62...kw==', 33) #=> true
298
+ #
299
+ # see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryChangeMessageVisibility.html
300
+ def change_message_visibility(queue_url, receipt_handle, visibility_timeout)
301
+ req_hash = generate_request('ChangeMessageVisibility',
302
+ 'ReceiptHandle' => receipt_handle,
303
+ 'VisibilityTimeout' => visibility_timeout,
304
+ :queue_url => queue_url )
305
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
306
+ rescue
307
+ on_exception
308
+ end
309
+
310
+ # Sends a new message to a queue. Message size is limited to 8 KB.
311
+ # If successful, this call returns a hash containing key/value pairs for
312
+ # "MessageId" and "MD5OfMessageBody":
313
+ #
314
+ # sqs.send_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'message_1') #=>
315
+ # {"MessageId"=>"MEs4M0JKNlRCRTBBSENaMjROTk58QVFRNzNEREhDVFlFOVJDQ1JKNjF8UTdBRllCUlJUMjhKMUI1WDJSWDE=",
316
+ # "MD5OfMessageBody"=>"16af2171b5b83cfa35ce254966ba81e3"}
317
+ #
318
+ # On failure, send_message raises an exception.
319
+ #
320
+ #
321
+ def send_message(queue_url, message)
322
+ req_hash = generate_post_request('SendMessage', :message => message, :queue_url => queue_url)
323
+ request_info(req_hash, SqsSendMessagesParser.new(:logger => @logger))
324
+ rescue
325
+ on_exception
326
+ end
327
+
328
+ # Same as send_message
329
+ alias_method :push_message, :send_message
330
+
331
+
332
+ # Deletes message from queue. Returns +true+ or an exception. Amazon
333
+ # returns +true+ on deletion of non-existent messages. You must use the
334
+ # receipt handle for a message to delete it, not the message ID.
335
+ #
336
+ # From the SQS Developer Guide:
337
+ # "It is possible you will receive a message even after you have deleted it. This might happen
338
+ # on rare occasions if one of the servers storing a copy of the message is unavailable when
339
+ # you request to delete the message. The copy remains on the server and might be returned to
340
+ # you again on a subsequent receive request. You should create your system to be
341
+ # idempotent so that receiving a particular message more than once is not a problem. "
342
+ #
343
+ # sqs.delete_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'Euvo62/1nlIet...ao03hd9Sa0w==') #=> true
344
+ #
345
+ def delete_message(queue_url, receipt_handle)
346
+ req_hash = generate_request('DeleteMessage', 'ReceiptHandle' => receipt_handle, :queue_url => queue_url)
347
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
348
+ rescue
349
+ on_exception
350
+ end
351
+
352
+ # Given the queue's short name, this call returns the queue URL or +nil+ if queue is not found
353
+ # sqs.queue_url_by_name('my_awesome_queue') #=> 'https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
354
+ #
355
+ def queue_url_by_name(queue_name)
356
+ return queue_name if queue_name.include?('/')
357
+ queue_urls = list_queues(queue_name)
358
+ queue_urls.each do |queue_url|
359
+ return queue_url if queue_name_by_url(queue_url) == queue_name
360
+ end
361
+ nil
362
+ rescue
363
+ on_exception
364
+ end
365
+
366
+ # Returns short queue name by url.
367
+ #
368
+ # RightSqs.queue_name_by_url('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
369
+ #
370
+ def self.queue_name_by_url(queue_url)
371
+ queue_url[/[^\/]*$/]
372
+ rescue
373
+ on_exception
374
+ end
375
+
376
+ # Returns short queue name by url.
377
+ #
378
+ # sqs.queue_name_by_url('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
379
+ #
380
+ def queue_name_by_url(queue_url)
381
+ self.class.queue_name_by_url(queue_url)
382
+ rescue
383
+ on_exception
384
+ end
385
+
386
+ # Returns approximate number of messages in queue.
387
+ #
388
+ # sqs.get_queue_length('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 3
389
+ #
390
+ def get_queue_length(queue_url)
391
+ attrs = get_queue_attributes(queue_url)
392
+ attrs['ApproximateNumberOfMessages'].to_i +
393
+ attrs['ApproximateNumberOfMessagesNotVisible'].to_i
394
+ rescue
395
+ on_exception
396
+ end
397
+
398
+ # Removes all visible messages from queue. Return +true+ or an exception.
399
+ #
400
+ # sqs.clear_queue('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> true
401
+ #
402
+ def clear_queue(queue_url)
403
+ while (pop_messages(queue_url, 10).length > 0) ; end # delete all messages in queue
404
+ true
405
+ rescue
406
+ on_exception
407
+ end
408
+
409
+ # 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>.
410
+ #
411
+ # sqs.pop_messages('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 3) #=>
412
+ # [{"ReceiptHandle"=>"Euvo62/...+Zw==", "MD5OfBody"=>"16af2...81e3", "Body"=>"Goodbyte World!",
413
+ # "MessageId"=>"MEZI...JSWDE="}, {...}, ... , {...} ]
414
+ #
415
+ def pop_messages(queue_url, number_of_messages=1, attributes=nil)
416
+ messages = receive_message(queue_url, number_of_messages, nil, attributes)
417
+ messages.each do |message|
418
+ delete_message(queue_url, message['ReceiptHandle'])
419
+ end
420
+ messages
421
+ rescue
422
+ on_exception
423
+ end
424
+
425
+ # Pops (retrieves and deletes) first accessible message from queue. Returns the message in format <tt>{:id=>'message_id', :body=>'message_body'}</tt> or +nil+.
426
+ #
427
+ # sqs.pop_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=>
428
+ # {:id=>"12345678904GEZX9746N|0N9ED344VK5Z3SV1DTM0|1RVYH4X3TJ0987654321", :body=>"message_1"}
429
+ #
430
+ def pop_message(queue_url, attributes=nil)
431
+ messages = pop_messages(queue_url, 1, attributes)
432
+ messages.blank? ? nil : messages[0]
433
+ rescue
434
+ on_exception
435
+ end
436
+
437
+ #-----------------------------------------------------------------
438
+ # PARSERS: Status Response Parser
439
+ #-----------------------------------------------------------------
440
+
441
+ class SqsStatusParser < RightAWSParser # :nodoc:
442
+ def tagend(name)
443
+ if name == 'ResponseMetadata'
444
+ @result = true
445
+ end
446
+ end
447
+ end
448
+
449
+ #-----------------------------------------------------------------
450
+ # PARSERS: Queue
451
+ #-----------------------------------------------------------------
452
+
453
+ class SqsCreateQueueParser < RightAWSParser # :nodoc:
454
+ def tagend(name)
455
+ @result = @text if name == 'QueueUrl'
456
+ end
457
+ end
458
+
459
+ class SqsListQueuesParser < RightAWSParser # :nodoc:
460
+ def reset
461
+ @result = []
462
+ end
463
+ def tagend(name)
464
+ @result << @text if name == 'QueueUrl'
465
+ end
466
+ end
467
+
468
+ class SqsGetQueueAttributesParser < RightAWSParser # :nodoc:
469
+ def reset
470
+ @result = {}
471
+ end
472
+ def tagend(name)
473
+ case name
474
+ when 'Name' then @current_attribute = @text
475
+ when 'Value' then @result[@current_attribute] = @text
476
+ end
477
+ end
478
+ end
479
+
480
+ #-----------------------------------------------------------------
481
+ # PARSERS: Messages
482
+ #-----------------------------------------------------------------
483
+
484
+ class SqsReceiveMessageParser < RightAWSParser # :nodoc:
485
+ def reset
486
+ @result = []
487
+ end
488
+ def tagstart(name, attributes)
489
+ case name
490
+ when 'Message' then @current_message = { }
491
+ when 'Attribute' then
492
+ @current_message['Attributes'] ||= {}
493
+ @current_attribute_name = ''
494
+ @current_attribute_value = ''
495
+ end
496
+ end
497
+ def tagend(name)
498
+ case name
499
+ when 'MessageId' then @current_message['MessageId'] = @text
500
+ when 'ReceiptHandle' then @current_message['ReceiptHandle'] = @text
501
+ when 'MD5OfBody' then @current_message['MD5OfBody'] = @text
502
+ when 'Name' then @current_attribute_name = @text
503
+ when 'Value' then @current_attribute_value = @text
504
+ when 'Attribute' then @current_message['Attributes'][@current_attribute_name] = @current_attribute_value
505
+ when 'Body' then @current_message['Body'] = @text; @result << @current_message
506
+ end
507
+ end
508
+ end
509
+
510
+ class SqsSendMessagesParser < RightAWSParser # :nodoc:
511
+ def reset
512
+ @result = {}
513
+ end
514
+ def tagend(name)
515
+ case name
516
+ when 'MessageId' then @result['MessageId'] = @text
517
+ when 'MD5OfMessageBody' then @result['MD5OfMessageBody'] = @text
518
+ end
519
+ end
520
+ end
521
+
522
+ end
523
+
524
+ end