talaris-right_aws 2.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (66) hide show
  1. data/History.txt +305 -0
  2. data/Manifest.txt +60 -0
  3. data/README.txt +163 -0
  4. data/Rakefile +104 -0
  5. data/lib/acf/right_acf_interface.rb +549 -0
  6. data/lib/acf/right_acf_invalidations.rb +144 -0
  7. data/lib/acf/right_acf_origin_access_identities.rb +230 -0
  8. data/lib/acf/right_acf_streaming_interface.rb +229 -0
  9. data/lib/acw/right_acw_interface.rb +248 -0
  10. data/lib/as/right_as_interface.rb +698 -0
  11. data/lib/awsbase/benchmark_fix.rb +39 -0
  12. data/lib/awsbase/right_awsbase.rb +1174 -0
  13. data/lib/awsbase/support.rb +35 -0
  14. data/lib/awsbase/version.rb +9 -0
  15. data/lib/ec2/right_ec2.rb +458 -0
  16. data/lib/ec2/right_ec2_ebs.rb +465 -0
  17. data/lib/ec2/right_ec2_images.rb +413 -0
  18. data/lib/ec2/right_ec2_instances.rb +785 -0
  19. data/lib/ec2/right_ec2_monitoring.rb +70 -0
  20. data/lib/ec2/right_ec2_placement_groups.rb +108 -0
  21. data/lib/ec2/right_ec2_reserved_instances.rb +174 -0
  22. data/lib/ec2/right_ec2_security_groups.rb +396 -0
  23. data/lib/ec2/right_ec2_spot_instances.rb +425 -0
  24. data/lib/ec2/right_ec2_tags.rb +139 -0
  25. data/lib/ec2/right_ec2_vpc.rb +583 -0
  26. data/lib/ec2/right_ec2_windows_mobility.rb +84 -0
  27. data/lib/elb/right_elb_interface.rb +571 -0
  28. data/lib/iam/right_iam_access_keys.rb +71 -0
  29. data/lib/iam/right_iam_groups.rb +195 -0
  30. data/lib/iam/right_iam_interface.rb +341 -0
  31. data/lib/iam/right_iam_mfa_devices.rb +67 -0
  32. data/lib/iam/right_iam_users.rb +251 -0
  33. data/lib/rds/right_rds_interface.rb +1309 -0
  34. data/lib/right_aws.rb +83 -0
  35. data/lib/route_53/right_route_53_interface.rb +630 -0
  36. data/lib/s3/right_s3.rb +1123 -0
  37. data/lib/s3/right_s3_interface.rb +1198 -0
  38. data/lib/sdb/active_sdb.rb +1107 -0
  39. data/lib/sdb/right_sdb_interface.rb +753 -0
  40. data/lib/sqs/right_sqs.rb +387 -0
  41. data/lib/sqs/right_sqs_gen2.rb +342 -0
  42. data/lib/sqs/right_sqs_gen2_interface.rb +523 -0
  43. data/lib/sqs/right_sqs_interface.rb +593 -0
  44. data/right_aws.gemspec +91 -0
  45. data/test/acf/test_helper.rb +2 -0
  46. data/test/acf/test_right_acf.rb +138 -0
  47. data/test/awsbase/test_helper.rb +2 -0
  48. data/test/awsbase/test_right_awsbase.rb +12 -0
  49. data/test/ec2/test_helper.rb +2 -0
  50. data/test/ec2/test_right_ec2.rb +108 -0
  51. data/test/http_connection.rb +87 -0
  52. data/test/rds/test_helper.rb +2 -0
  53. data/test/rds/test_right_rds.rb +120 -0
  54. data/test/s3/test_helper.rb +2 -0
  55. data/test/s3/test_right_s3.rb +421 -0
  56. data/test/s3/test_right_s3_stubbed.rb +97 -0
  57. data/test/sdb/test_active_sdb.rb +357 -0
  58. data/test/sdb/test_batch_put_attributes.rb +54 -0
  59. data/test/sdb/test_helper.rb +3 -0
  60. data/test/sdb/test_right_sdb.rb +253 -0
  61. data/test/sqs/test_helper.rb +2 -0
  62. data/test/sqs/test_right_sqs.rb +285 -0
  63. data/test/sqs/test_right_sqs_gen2.rb +264 -0
  64. data/test/test_credentials.rb +37 -0
  65. data/test/ts_right_aws.rb +14 -0
  66. metadata +214 -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', {: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
+ # :signature_version => '0' # The signature version : '0', '1' or '2'(default)
75
+ # :logger => Logger Object} # Logger instance: logs to STDOUT if omitted }
76
+ #
77
+ def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
78
+ init({ :name => 'SQS',
79
+ :default_host => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).host : DEFAULT_HOST,
80
+ :default_port => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).port : DEFAULT_PORT,
81
+ :default_protocol => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).scheme : DEFAULT_PROTOCOL },
82
+ aws_access_key_id || ENV['AWS_ACCESS_KEY_ID'],
83
+ aws_secret_access_key || ENV['AWS_SECRET_ACCESS_KEY'],
84
+ params)
85
+ end
86
+
87
+
88
+ #-----------------------------------------------------------------
89
+ # Requests
90
+ #-----------------------------------------------------------------
91
+
92
+ # Generates a request hash for the query API
93
+ def generate_request(action, param={}) # :nodoc:
94
+ # For operation requests on a queue, the queue URI will be a parameter,
95
+ # so we first extract it from the call parameters. Next we remove any
96
+ # parameters with no value or with symbolic keys. We add the header
97
+ # fields required in all requests, and then the headers passed in as
98
+ # params. We sort the header fields alphabetically and then generate the
99
+ # signature before URL escaping the resulting query and sending it.
100
+ service = param[:queue_url] ? URI(param[:queue_url]).path : '/'
101
+ param.each{ |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
102
+ service_hash = { "Action" => action,
103
+ "Expires" => (Time.now + REQUEST_TTL).utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
104
+ "AWSAccessKeyId" => @aws_access_key_id,
105
+ "Version" => API_VERSION }
106
+ service_hash.update(param)
107
+ service_params = signed_service_params(@aws_secret_access_key, service_hash, :get, @params[:server], service)
108
+ request = Net::HTTP::Get.new("#{AwsUtils.URLencode(service)}?#{service_params}")
109
+ # prepare output hash
110
+ { :request => request,
111
+ :server => @params[:server],
112
+ :port => @params[:port],
113
+ :protocol => @params[:protocol] }
114
+ end
115
+
116
+ def generate_post_request(action, param={}) # :nodoc:
117
+ service = param[:queue_url] ? URI(param[:queue_url]).path : '/'
118
+ message = param[:message] # extract message body if nesessary
119
+ param.each{ |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
120
+ service_hash = { "Action" => action,
121
+ "Expires" => (Time.now + REQUEST_TTL).utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
122
+ "AWSAccessKeyId" => @aws_access_key_id,
123
+ "MessageBody" => message,
124
+ "Version" => API_VERSION }
125
+ service_hash.update(param)
126
+ #
127
+ service_params = signed_service_params(@aws_secret_access_key, service_hash, :post, @params[:server], service)
128
+ request = Net::HTTP::Post.new(AwsUtils::URLencode(service))
129
+ request['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
130
+ request.body = service_params
131
+ # prepare output hash
132
+ { :request => request,
133
+ :server => @params[:server],
134
+ :port => @params[:port],
135
+ :protocol => @params[:protocol] }
136
+ end
137
+
138
+
139
+ # Sends request to Amazon and parses the response
140
+ # Raises AwsError if any banana happened
141
+ def request_info(request, parser) # :nodoc:
142
+ request_info_impl(:sqs_connection, @@bench, request, parser)
143
+ end
144
+
145
+ # Creates a new queue, returning its URI.
146
+ #
147
+ # sqs.create_queue('my_awesome_queue') #=> 'https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
148
+ #
149
+ def create_queue(queue_name, default_visibility_timeout=nil)
150
+ req_hash = generate_request('CreateQueue', 'QueueName' => queue_name,
151
+ 'DefaultVisibilityTimeout' => default_visibility_timeout || DEFAULT_VISIBILITY_TIMEOUT )
152
+ request_info(req_hash, SqsCreateQueueParser.new(:logger => @logger))
153
+ rescue
154
+ on_exception
155
+ end
156
+
157
+ # Lists all queues owned by this user that have names beginning with +queue_name_prefix+.
158
+ # If +queue_name_prefix+ is omitted then retrieves a list of all queues.
159
+ # Queue creation is an eventual operation and created queues may not show up in immediately subsequent list_queues calls.
160
+ #
161
+ # sqs.create_queue('my_awesome_queue')
162
+ # sqs.create_queue('my_awesome_queue_2')
163
+ # sqs.list_queues('my_awesome') #=> ['https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue','https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2']
164
+ #
165
+ def list_queues(queue_name_prefix=nil)
166
+ req_hash = generate_request('ListQueues', 'QueueNamePrefix' => queue_name_prefix)
167
+ request_info(req_hash, SqsListQueuesParser.new(:logger => @logger))
168
+ rescue
169
+ on_exception
170
+ end
171
+
172
+ # Deletes queue. Any messages in the queue are permanently lost.
173
+ # Returns +true+ or an exception.
174
+ # Queue deletion can take up to 60 s to propagate through SQS. Thus, after a deletion, subsequent list_queues calls
175
+ # may still show the deleted queue. It is not unusual within the 60 s window to see the deleted queue absent from
176
+ # one list_queues call but present in the subsequent one. Deletion is eventual.
177
+ #
178
+ # sqs.delete_queue('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2') #=> true
179
+ #
180
+ def delete_queue(queue_url)
181
+ req_hash = generate_request('DeleteQueue', :queue_url => queue_url)
182
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
183
+ rescue
184
+ on_exception
185
+ end
186
+
187
+ # Retrieves the queue attribute(s). Returns a hash of attribute(s) or an exception.
188
+ #
189
+ # sqs.get_queue_attributes('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=>
190
+ # {"ApproximateNumberOfMessages" => "0",
191
+ # "LastModifiedTimestamp" => "1240946032",
192
+ # "CreatedTimestamp" => "1240816887",
193
+ # "VisibilityTimeout" => "30",
194
+ # "Policy" => "{"Version":"2008-10-17","Id":...}"}
195
+ #
196
+ # queue.get_queue_attributes('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', "LastModifiedTimestamp", "VisibilityTimeout") #=>
197
+ # {"LastModifiedTimestamp" => "1240946032",
198
+ # "VisibilityTimeout" => "30"}
199
+ #
200
+ # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryGetQueueAttributes.html
201
+ def get_queue_attributes(queue_url, *attributes)
202
+ attributes.flatten!
203
+ attributes << 'All' if attributes.right_blank?
204
+ params = amazonize_list('AttributeName', attributes)
205
+ params.merge!(:queue_url => queue_url)
206
+ req_hash = generate_request('GetQueueAttributes', params)
207
+ request_info(req_hash, SqsGetQueueAttributesParser.new(:logger => @logger))
208
+ rescue
209
+ on_exception
210
+ end
211
+
212
+ # Sets queue attribute. Returns +true+ or an exception.
213
+ #
214
+ # sqs.set_queue_attributes('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', "VisibilityTimeout", 10) #=> true
215
+ #
216
+ # From the SQS Dev Guide:
217
+ # "When you change a queue's attributes, the change can take up to 60 seconds to propagate
218
+ # throughout the SQS system."
219
+ #
220
+ # NB: Attribute values may not be immediately available to other queries
221
+ # for some time after an update. See the SQS documentation for
222
+ # semantics, but in general propagation can take up to 60 s.
223
+ #
224
+ # see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QuerySetQueueAttributes.html
225
+ def set_queue_attributes(queue_url, attribute, value)
226
+ req_hash = generate_request('SetQueueAttributes',
227
+ 'Attribute.Name' => attribute,
228
+ 'Attribute.Value' => value,
229
+ :queue_url => queue_url)
230
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
231
+ rescue
232
+ on_exception
233
+ end
234
+
235
+ # Add permissions to a queue.
236
+ #
237
+ # sqs.add_permissions('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',
238
+ # 'testLabel', ['125074342641','125074342642'],
239
+ # ['SendMessage','SendMessage','ReceiveMessage']) #=> true
240
+ #
241
+ # +permissions+ is a hash of: AccountId => ActionName
242
+ # (valid ActionNames: * | SendMessage | ReceiveMessage | DeleteMessage | ChangeMessageVisibility | GetQueueAttributes )
243
+ #
244
+ # see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryAddPermission.html
245
+ # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?acp-overview.html
246
+ def add_permissions(queue_url, label, grantees, actions)
247
+ params = amazonize_list('AWSAccountId', Array(grantees))
248
+ params.merge!(amazonize_list('ActionName', Array(actions)))
249
+ params.merge!('Label' => label,
250
+ :queue_url => queue_url )
251
+ req_hash = generate_request('AddPermission', params)
252
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
253
+ rescue
254
+ on_exception
255
+ end
256
+
257
+ # Revoke any permissions in the queue policy that matches the +label+ parameter.
258
+ #
259
+ # sqs.remove_permissions('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',
260
+ # 'testLabel') # => true
261
+ #
262
+ # see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryRemovePermission.html
263
+ def remove_permissions(queue_url, label)
264
+ req_hash = generate_request('RemovePermission',
265
+ 'Label' => label,
266
+ :queue_url => queue_url )
267
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
268
+ rescue
269
+ on_exception
270
+ end
271
+
272
+ # Retrieves a list of messages from queue. Returns an array of hashes in format: <tt>{:id=>'message_id', :body=>'message_body'}</tt>
273
+ #
274
+ # sqs.receive_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',10, 5) #=>
275
+ # [{"ReceiptHandle"=>"Euvo62...kw==", "MD5OfBody"=>"16af2171b5b83cfa35ce254966ba81e3",
276
+ # "Body"=>"Goodbyte World!", "MessageId"=>"MUM4WlAyR...pYOTA="}, ..., {}]
277
+ #
278
+ # Normally this call returns fewer messages than the maximum specified,
279
+ # even if they are available.
280
+ #
281
+ def receive_message(queue_url, max_number_of_messages=1, visibility_timeout=nil, attributes=nil)
282
+ return [] if max_number_of_messages == 0
283
+ params = {}
284
+ params.merge!(amazonize_list('AttributeName', Array(attributes))) unless attributes.right_blank?
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.right_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