ijin-right_aws 1.11.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (50) hide show
  1. data/History.txt +239 -0
  2. data/Manifest.txt +46 -0
  3. data/README.txt +167 -0
  4. data/Rakefile +125 -0
  5. data/VERSION +1 -0
  6. data/lib/acf/right_acf_interface.rb +413 -0
  7. data/lib/acw/right_acw_interface.rb +249 -0
  8. data/lib/as/right_as_interface.rb +690 -0
  9. data/lib/awsbase/benchmark_fix.rb +39 -0
  10. data/lib/awsbase/right_awsbase.rb +931 -0
  11. data/lib/awsbase/support.rb +115 -0
  12. data/lib/ec2/right_ec2.rb +617 -0
  13. data/lib/ec2/right_ec2_ebs.rb +451 -0
  14. data/lib/ec2/right_ec2_images.rb +373 -0
  15. data/lib/ec2/right_ec2_instances.rb +760 -0
  16. data/lib/ec2/right_ec2_monitoring.rb +70 -0
  17. data/lib/ec2/right_ec2_reserved_instances.rb +167 -0
  18. data/lib/ec2/right_ec2_vpc.rb +571 -0
  19. data/lib/elb/right_elb_interface.rb +407 -0
  20. data/lib/rds/right_rds_interface.rb +998 -0
  21. data/lib/right_aws.rb +79 -0
  22. data/lib/s3/right_s3.rb +1102 -0
  23. data/lib/s3/right_s3_interface.rb +1195 -0
  24. data/lib/sdb/active_sdb.rb +930 -0
  25. data/lib/sdb/right_sdb_interface.rb +672 -0
  26. data/lib/sqs/right_sqs.rb +388 -0
  27. data/lib/sqs/right_sqs_gen2.rb +343 -0
  28. data/lib/sqs/right_sqs_gen2_interface.rb +523 -0
  29. data/lib/sqs/right_sqs_interface.rb +594 -0
  30. data/test/acf/test_helper.rb +2 -0
  31. data/test/acf/test_right_acf.rb +146 -0
  32. data/test/awsbase/test_helper.rb +2 -0
  33. data/test/awsbase/test_right_awsbase.rb +12 -0
  34. data/test/ec2/test_helper.rb +2 -0
  35. data/test/ec2/test_right_ec2.rb +108 -0
  36. data/test/http_connection.rb +87 -0
  37. data/test/rds/test_helper.rb +2 -0
  38. data/test/rds/test_right_rds.rb +120 -0
  39. data/test/s3/test_helper.rb +2 -0
  40. data/test/s3/test_right_s3.rb +419 -0
  41. data/test/s3/test_right_s3_stubbed.rb +95 -0
  42. data/test/sdb/test_active_sdb.rb +299 -0
  43. data/test/sdb/test_helper.rb +3 -0
  44. data/test/sdb/test_right_sdb.rb +247 -0
  45. data/test/sqs/test_helper.rb +2 -0
  46. data/test/sqs/test_right_sqs.rb +291 -0
  47. data/test/sqs/test_right_sqs_gen2.rb +276 -0
  48. data/test/test_credentials.rb +37 -0
  49. data/test/ts_right_aws.rb +14 -0
  50. metadata +122 -0
@@ -0,0 +1,523 @@
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'
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.to_a)
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', grantees.to_a)
249
+ params.merge!(amazonize_list('ActionName', actions.to_a))
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 = amazonize_list('AttributeName', attributes.to_a)
285
+ params.merge!('MaxNumberOfMessages' => max_number_of_messages,
286
+ 'VisibilityTimeout' => visibility_timeout,
287
+ :queue_url => queue_url )
288
+ req_hash = generate_post_request('ReceiveMessage', params)
289
+ request_info(req_hash, SqsReceiveMessageParser.new(:logger => @logger))
290
+ rescue
291
+ on_exception
292
+ end
293
+
294
+ # Change the visibility timeout of a specified message in a queue.
295
+ #
296
+ # sqs.change_message_visibility('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'Euvo62...kw==', 33) #=> true
297
+ #
298
+ # see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryChangeMessageVisibility.html
299
+ def change_message_visibility(queue_url, receipt_handle, visibility_timeout)
300
+ req_hash = generate_request('ChangeMessageVisibility',
301
+ 'ReceiptHandle' => receipt_handle,
302
+ 'VisibilityTimeout' => visibility_timeout,
303
+ :queue_url => queue_url )
304
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
305
+ rescue
306
+ on_exception
307
+ end
308
+
309
+ # Sends a new message to a queue. Message size is limited to 8 KB.
310
+ # If successful, this call returns a hash containing key/value pairs for
311
+ # "MessageId" and "MD5OfMessageBody":
312
+ #
313
+ # sqs.send_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'message_1') #=>
314
+ # {"MessageId"=>"MEs4M0JKNlRCRTBBSENaMjROTk58QVFRNzNEREhDVFlFOVJDQ1JKNjF8UTdBRllCUlJUMjhKMUI1WDJSWDE=",
315
+ # "MD5OfMessageBody"=>"16af2171b5b83cfa35ce254966ba81e3"}
316
+ #
317
+ # On failure, send_message raises an exception.
318
+ #
319
+ #
320
+ def send_message(queue_url, message)
321
+ req_hash = generate_post_request('SendMessage', :message => message, :queue_url => queue_url)
322
+ request_info(req_hash, SqsSendMessagesParser.new(:logger => @logger))
323
+ rescue
324
+ on_exception
325
+ end
326
+
327
+ # Same as send_message
328
+ alias_method :push_message, :send_message
329
+
330
+
331
+ # Deletes message from queue. Returns +true+ or an exception. Amazon
332
+ # returns +true+ on deletion of non-existent messages. You must use the
333
+ # receipt handle for a message to delete it, not the message ID.
334
+ #
335
+ # From the SQS Developer Guide:
336
+ # "It is possible you will receive a message even after you have deleted it. This might happen
337
+ # on rare occasions if one of the servers storing a copy of the message is unavailable when
338
+ # you request to delete the message. The copy remains on the server and might be returned to
339
+ # you again on a subsequent receive request. You should create your system to be
340
+ # idempotent so that receiving a particular message more than once is not a problem. "
341
+ #
342
+ # sqs.delete_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'Euvo62/1nlIet...ao03hd9Sa0w==') #=> true
343
+ #
344
+ def delete_message(queue_url, receipt_handle)
345
+ req_hash = generate_request('DeleteMessage', 'ReceiptHandle' => receipt_handle, :queue_url => queue_url)
346
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
347
+ rescue
348
+ on_exception
349
+ end
350
+
351
+ # Given the queue's short name, this call returns the queue URL or +nil+ if queue is not found
352
+ # sqs.queue_url_by_name('my_awesome_queue') #=> 'https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
353
+ #
354
+ def queue_url_by_name(queue_name)
355
+ return queue_name if queue_name.include?('/')
356
+ queue_urls = list_queues(queue_name)
357
+ queue_urls.each do |queue_url|
358
+ return queue_url if queue_name_by_url(queue_url) == queue_name
359
+ end
360
+ nil
361
+ rescue
362
+ on_exception
363
+ end
364
+
365
+ # Returns short queue name by url.
366
+ #
367
+ # RightSqs.queue_name_by_url('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
368
+ #
369
+ def self.queue_name_by_url(queue_url)
370
+ queue_url[/[^\/]*$/]
371
+ rescue
372
+ on_exception
373
+ end
374
+
375
+ # Returns short queue name by url.
376
+ #
377
+ # sqs.queue_name_by_url('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
378
+ #
379
+ def queue_name_by_url(queue_url)
380
+ self.class.queue_name_by_url(queue_url)
381
+ rescue
382
+ on_exception
383
+ end
384
+
385
+ # Returns approximate number of messages in queue.
386
+ #
387
+ # sqs.get_queue_length('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 3
388
+ #
389
+ def get_queue_length(queue_url)
390
+ attrs = get_queue_attributes(queue_url)
391
+ attrs['ApproximateNumberOfMessages'].to_i +
392
+ attrs['ApproximateNumberOfMessagesNotVisible'].to_i
393
+ rescue
394
+ on_exception
395
+ end
396
+
397
+ # Removes all visible messages from queue. Return +true+ or an exception.
398
+ #
399
+ # sqs.clear_queue('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> true
400
+ #
401
+ def clear_queue(queue_url)
402
+ while (pop_messages(queue_url, 10).length > 0) ; end # delete all messages in queue
403
+ true
404
+ rescue
405
+ on_exception
406
+ end
407
+
408
+ # 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>.
409
+ #
410
+ # sqs.pop_messages('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 3) #=>
411
+ # [{"ReceiptHandle"=>"Euvo62/...+Zw==", "MD5OfBody"=>"16af2...81e3", "Body"=>"Goodbyte World!",
412
+ # "MessageId"=>"MEZI...JSWDE="}, {...}, ... , {...} ]
413
+ #
414
+ def pop_messages(queue_url, number_of_messages=1, attributes=nil)
415
+ messages = receive_message(queue_url, number_of_messages, nil, attributes)
416
+ messages.each do |message|
417
+ delete_message(queue_url, message['ReceiptHandle'])
418
+ end
419
+ messages
420
+ rescue
421
+ on_exception
422
+ end
423
+
424
+ # Pops (retrieves and deletes) first accessible message from queue. Returns the message in format <tt>{:id=>'message_id', :body=>'message_body'}</tt> or +nil+.
425
+ #
426
+ # sqs.pop_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=>
427
+ # {:id=>"12345678904GEZX9746N|0N9ED344VK5Z3SV1DTM0|1RVYH4X3TJ0987654321", :body=>"message_1"}
428
+ #
429
+ def pop_message(queue_url, attributes=nil)
430
+ messages = pop_messages(queue_url, 1, attributes)
431
+ messages.blank? ? nil : messages[0]
432
+ rescue
433
+ on_exception
434
+ end
435
+
436
+ #-----------------------------------------------------------------
437
+ # PARSERS: Status Response Parser
438
+ #-----------------------------------------------------------------
439
+
440
+ class SqsStatusParser < RightAWSParser # :nodoc:
441
+ def tagend(name)
442
+ if name == 'ResponseMetadata'
443
+ @result = true
444
+ end
445
+ end
446
+ end
447
+
448
+ #-----------------------------------------------------------------
449
+ # PARSERS: Queue
450
+ #-----------------------------------------------------------------
451
+
452
+ class SqsCreateQueueParser < RightAWSParser # :nodoc:
453
+ def tagend(name)
454
+ @result = @text if name == 'QueueUrl'
455
+ end
456
+ end
457
+
458
+ class SqsListQueuesParser < RightAWSParser # :nodoc:
459
+ def reset
460
+ @result = []
461
+ end
462
+ def tagend(name)
463
+ @result << @text if name == 'QueueUrl'
464
+ end
465
+ end
466
+
467
+ class SqsGetQueueAttributesParser < RightAWSParser # :nodoc:
468
+ def reset
469
+ @result = {}
470
+ end
471
+ def tagend(name)
472
+ case name
473
+ when 'Name' then @current_attribute = @text
474
+ when 'Value' then @result[@current_attribute] = @text
475
+ end
476
+ end
477
+ end
478
+
479
+ #-----------------------------------------------------------------
480
+ # PARSERS: Messages
481
+ #-----------------------------------------------------------------
482
+
483
+ class SqsReceiveMessageParser < RightAWSParser # :nodoc:
484
+ def reset
485
+ @result = []
486
+ end
487
+ def tagstart(name, attributes)
488
+ case name
489
+ when 'Message' then @current_message = { }
490
+ when 'Attribute' then
491
+ @current_message['Attributes'] ||= {}
492
+ @current_attribute_name = ''
493
+ @current_attribute_value = ''
494
+ end
495
+ end
496
+ def tagend(name)
497
+ case name
498
+ when 'MessageId' then @current_message['MessageId'] = @text
499
+ when 'ReceiptHandle' then @current_message['ReceiptHandle'] = @text
500
+ when 'MD5OfBody' then @current_message['MD5OfBody'] = @text
501
+ when 'Name' then @current_attribute_name = @text
502
+ when 'Value' then @current_attribute_value = @text
503
+ when 'Attribute' then @current_message['Attributes'][@current_attribute_name] = @current_attribute_value
504
+ when 'Body' then @current_message['Body'] = @text; @result << @current_message
505
+ end
506
+ end
507
+ end
508
+
509
+ class SqsSendMessagesParser < RightAWSParser # :nodoc:
510
+ def reset
511
+ @result = {}
512
+ end
513
+ def tagend(name)
514
+ case name
515
+ when 'MessageId' then @result['MessageId'] = @text
516
+ when 'MD5OfMessageBody' then @result['MD5OfMessageBody'] = @text
517
+ end
518
+ end
519
+ end
520
+
521
+ end
522
+
523
+ end