dmarkov-right_aws 1.10.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,444 @@
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 = "2008-01-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' 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
+ 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
+ thread = @params[:multi_thread] ? Thread.current : Thread.main
144
+ thread[:sqs_connection] ||= Rightscale::HttpConnection.new(:exception => AwsError, :logger => @logger)
145
+ request_info_impl(thread[:sqs_connection], @@bench, request, parser)
146
+ end
147
+
148
+
149
+ # Creates a new queue, returning its URI.
150
+ #
151
+ # sqs.create_queue('my_awesome_queue') #=> 'http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
152
+ #
153
+ def create_queue(queue_name, default_visibility_timeout=nil)
154
+ req_hash = generate_request('CreateQueue', 'QueueName' => queue_name,
155
+ 'DefaultVisibilityTimeout' => default_visibility_timeout || DEFAULT_VISIBILITY_TIMEOUT )
156
+ request_info(req_hash, SqsCreateQueueParser.new(:logger => @logger))
157
+ rescue
158
+ on_exception
159
+ end
160
+
161
+ # Lists all queues owned by this user that have names beginning with +queue_name_prefix+.
162
+ # If +queue_name_prefix+ is omitted then retrieves a list of all queues.
163
+ # Queue creation is an eventual operation and created queues may not show up in immediately subsequent list_queues calls.
164
+ #
165
+ # sqs.create_queue('my_awesome_queue')
166
+ # sqs.create_queue('my_awesome_queue_2')
167
+ # sqs.list_queues('my_awesome') #=> ['http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue','http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2']
168
+ #
169
+ def list_queues(queue_name_prefix=nil)
170
+ req_hash = generate_request('ListQueues', 'QueueNamePrefix' => queue_name_prefix)
171
+ request_info(req_hash, SqsListQueuesParser.new(:logger => @logger))
172
+ rescue
173
+ on_exception
174
+ end
175
+
176
+ # Deletes queue. Any messages in the queue are permanently lost.
177
+ # Returns +true+ or an exception.
178
+ # Queue deletion can take up to 60 s to propagate through SQS. Thus, after a deletion, subsequent list_queues calls
179
+ # may still show the deleted queue. It is not unusual within the 60 s window to see the deleted queue absent from
180
+ # one list_queues call but present in the subsequent one. Deletion is eventual.
181
+ #
182
+ # sqs.delete_queue('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2') #=> true
183
+ #
184
+ #
185
+ def delete_queue(queue_url)
186
+ req_hash = generate_request('DeleteQueue', :queue_url => queue_url)
187
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
188
+ rescue
189
+ on_exception
190
+ end
191
+
192
+ # Retrieves the queue attribute(s). Returns a hash of attribute(s) or an exception.
193
+ #
194
+ # sqs.get_queue_attributes('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue')
195
+ # #=> {"ApproximateNumberOfMessages"=>"0", "VisibilityTimeout"=>"30"}
196
+ #
197
+ def get_queue_attributes(queue_url, attribute='All')
198
+ req_hash = generate_request('GetQueueAttributes', 'AttributeName' => attribute, :queue_url => queue_url)
199
+ request_info(req_hash, SqsGetQueueAttributesParser.new(:logger => @logger))
200
+ rescue
201
+ on_exception
202
+ end
203
+
204
+ # Sets queue attribute. Returns +true+ or an exception.
205
+ #
206
+ # sqs.set_queue_attributes('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', "VisibilityTimeout", 10) #=> true
207
+ #
208
+ # From the SQS Dev Guide:
209
+ # "Currently, you can set only the
210
+ # VisibilityTimeout attribute for a queue...
211
+ # When you change a queue's attributes, the change can take up to 60 seconds to propagate
212
+ # throughout the SQS system."
213
+ #
214
+ # NB: Attribute values may not be immediately available to other queries
215
+ # for some time after an update. See the SQS documentation for
216
+ # semantics, but in general propagation can take up to 60 s.
217
+ def set_queue_attributes(queue_url, attribute, value)
218
+ req_hash = generate_request('SetQueueAttributes', 'Attribute.Name' => attribute, 'Attribute.Value' => value, :queue_url => queue_url)
219
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
220
+ rescue
221
+ on_exception
222
+ end
223
+
224
+ # Retrieves a list of messages from queue. Returns an array of hashes in format: <tt>{:id=>'message_id', body=>'message_body'}</tt>
225
+ #
226
+ # sqs.receive_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',10, 5) #=>
227
+ # [{"ReceiptHandle"=>"Euvo62...kw==", "MD5OfBody"=>"16af2171b5b83cfa35ce254966ba81e3",
228
+ # "Body"=>"Goodbyte World!", "MessageId"=>"MUM4WlAyR...pYOTA="}, ..., {}]
229
+ #
230
+ # Normally this call returns fewer messages than the maximum specified,
231
+ # even if they are available.
232
+ #
233
+ def receive_message(queue_url, max_number_of_messages=1, visibility_timeout=nil)
234
+ return [] if max_number_of_messages == 0
235
+ req_hash = generate_post_request('ReceiveMessage', 'MaxNumberOfMessages' => max_number_of_messages, 'VisibilityTimeout' => visibility_timeout,
236
+ :queue_url => queue_url )
237
+ request_info(req_hash, SqsReceiveMessageParser.new(:logger => @logger))
238
+ rescue
239
+ on_exception
240
+ end
241
+
242
+ # Sends a new message to a queue. Message size is limited to 8 KB.
243
+ # If successful, this call returns a hash containing key/value pairs for
244
+ # "MessageId" and "MD5OfMessageBody":
245
+ #
246
+ # sqs.send_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'message_1') #=> "1234567890...0987654321"
247
+ # => {"MessageId"=>"MEs4M0JKNlRCRTBBSENaMjROTk58QVFRNzNEREhDVFlFOVJDQ1JKNjF8UTdBRllCUlJUMjhKMUI1WDJSWDE=", "MD5OfMessageBody"=>"16af2171b5b83cfa35ce254966ba81e3"}
248
+ #
249
+ # On failure, send_message raises an exception.
250
+ #
251
+ #
252
+ def send_message(queue_url, message)
253
+ req_hash = generate_post_request('SendMessage', :message => message, :queue_url => queue_url)
254
+ request_info(req_hash, SqsSendMessagesParser.new(:logger => @logger))
255
+ rescue
256
+ on_exception
257
+ end
258
+
259
+ # Same as send_message
260
+ alias_method :push_message, :send_message
261
+
262
+
263
+ # Deletes message from queue. Returns +true+ or an exception. Amazon
264
+ # returns +true+ on deletion of non-existent messages. You must use the
265
+ # receipt handle for a message to delete it, not the message ID.
266
+ #
267
+ # From the SQS Developer Guide:
268
+ # "It is possible you will receive a message even after you have deleted it. This might happen
269
+ # on rare occasions if one of the servers storing a copy of the message is unavailable when
270
+ # you request to delete the message. The copy remains on the server and might be returned to
271
+ # you again on a subsequent receive request. You should create your system to be
272
+ # idempotent so that receiving a particular message more than once is not a problem. "
273
+ #
274
+ # sqs.delete_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'Euvo62/1nlIet...ao03hd9Sa0w==') #=> true
275
+ #
276
+ def delete_message(queue_url, receipt_handle)
277
+ req_hash = generate_request('DeleteMessage', 'ReceiptHandle' => receipt_handle, :queue_url => queue_url)
278
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
279
+ rescue
280
+ on_exception
281
+ end
282
+
283
+ # Given the queue's short name, this call returns the queue URL or +nil+ if queue is not found
284
+ # sqs.queue_url_by_name('my_awesome_queue') #=> 'http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
285
+ #
286
+ def queue_url_by_name(queue_name)
287
+ return queue_name if queue_name.include?('/')
288
+ queue_urls = list_queues(queue_name)
289
+ queue_urls.each do |queue_url|
290
+ return queue_url if queue_name_by_url(queue_url) == queue_name
291
+ end
292
+ nil
293
+ rescue
294
+ on_exception
295
+ end
296
+
297
+ # Returns short queue name by url.
298
+ #
299
+ # RightSqs.queue_name_by_url('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
300
+ #
301
+ def self.queue_name_by_url(queue_url)
302
+ queue_url[/[^\/]*$/]
303
+ rescue
304
+ on_exception
305
+ end
306
+
307
+ # Returns short queue name by url.
308
+ #
309
+ # sqs.queue_name_by_url('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
310
+ #
311
+ def queue_name_by_url(queue_url)
312
+ self.class.queue_name_by_url(queue_url)
313
+ rescue
314
+ on_exception
315
+ end
316
+
317
+ # Returns approximate number of messages in queue.
318
+ #
319
+ # sqs.get_queue_length('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 3
320
+ #
321
+ def get_queue_length(queue_url)
322
+ get_queue_attributes(queue_url)['ApproximateNumberOfMessages'].to_i
323
+ rescue
324
+ on_exception
325
+ end
326
+
327
+ # Removes all visible messages from queue. Return +true+ or an exception.
328
+ #
329
+ # sqs.clear_queue('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> true
330
+ #
331
+ def clear_queue(queue_url)
332
+ while (pop_messages(queue_url, 10).length > 0) ; end # delete all messages in queue
333
+ true
334
+ rescue
335
+ on_exception
336
+ end
337
+
338
+ # 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>.
339
+ #
340
+ # sqs.pop_messages('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 3) #=>
341
+ # [{"ReceiptHandle"=>"Euvo62/...+Zw==", "MD5OfBody"=>"16af2...81e3", "Body"=>"Goodbyte World!",
342
+ # "MessageId"=>"MEZI...JSWDE="}, {...}, ... , {...} ]
343
+ #
344
+ def pop_messages(queue_url, number_of_messages=1)
345
+ messages = receive_message(queue_url, number_of_messages)
346
+ messages.each do |message|
347
+ delete_message(queue_url, message['ReceiptHandle'])
348
+ end
349
+ messages
350
+ rescue
351
+ on_exception
352
+ end
353
+
354
+ # Pops (retrieves and deletes) first accessible message from queue. Returns the message in format <tt>{:id=>'message_id', :body=>'message_body'}</tt> or +nil+.
355
+ #
356
+ # sqs.pop_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=>
357
+ # {:id=>"12345678904GEZX9746N|0N9ED344VK5Z3SV1DTM0|1RVYH4X3TJ0987654321", :body=>"message_1"}
358
+ #
359
+ def pop_message(queue_url)
360
+ messages = pop_messages(queue_url)
361
+ messages.blank? ? nil : messages[0]
362
+ rescue
363
+ on_exception
364
+ end
365
+
366
+ #-----------------------------------------------------------------
367
+ # PARSERS: Status Response Parser
368
+ #-----------------------------------------------------------------
369
+
370
+ class SqsStatusParser < RightAWSParser # :nodoc:
371
+ def tagend(name)
372
+ if name == 'ResponseMetadata'
373
+ @result = true
374
+ end
375
+ end
376
+ end
377
+
378
+ #-----------------------------------------------------------------
379
+ # PARSERS: Queue
380
+ #-----------------------------------------------------------------
381
+
382
+ class SqsCreateQueueParser < RightAWSParser # :nodoc:
383
+ def tagend(name)
384
+ @result = @text if name == 'QueueUrl'
385
+ end
386
+ end
387
+
388
+ class SqsListQueuesParser < RightAWSParser # :nodoc:
389
+ def reset
390
+ @result = []
391
+ end
392
+ def tagend(name)
393
+ @result << @text if name == 'QueueUrl'
394
+ end
395
+ end
396
+
397
+ class SqsGetQueueAttributesParser < RightAWSParser # :nodoc:
398
+ def reset
399
+ @result = {}
400
+ end
401
+ def tagend(name)
402
+ case name
403
+ when 'Name' ; @current_attribute = @text
404
+ when 'Value' ; @result[@current_attribute] = @text
405
+ end
406
+ end
407
+ end
408
+
409
+ #-----------------------------------------------------------------
410
+ # PARSERS: Messages
411
+ #-----------------------------------------------------------------
412
+
413
+ class SqsReceiveMessageParser < RightAWSParser # :nodoc:
414
+ def reset
415
+ @result = []
416
+ end
417
+ def tagstart(name, attributes)
418
+ @current_message = {} if name == 'Message'
419
+ end
420
+ def tagend(name)
421
+ case name
422
+ when 'MessageId' ; @current_message['MessageId'] = @text
423
+ when 'ReceiptHandle' ; @current_message['ReceiptHandle'] = @text
424
+ when 'MD5OfBody' ; @current_message['MD5OfBody'] = @text
425
+ when 'Body'; @current_message['Body'] = @text; @result << @current_message
426
+ end
427
+ end
428
+ end
429
+
430
+ class SqsSendMessagesParser < RightAWSParser # :nodoc:
431
+ def reset
432
+ @result = {}
433
+ end
434
+ def tagend(name)
435
+ case name
436
+ when 'MessageId' ; @result['MessageId'] = @text
437
+ when 'MD5OfMessageBody' ; @result['MD5OfMessageBody'] = @text
438
+ end
439
+ end
440
+ end
441
+
442
+ end
443
+
444
+ end
@@ -0,0 +1,596 @@
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
+ class SqsInterface < RightAwsBase
27
+ include RightAwsBaseInterface
28
+
29
+ API_VERSION = "2007-05-01"
30
+ DEFAULT_HOST = "queue.amazonaws.com"
31
+ DEFAULT_PORT = 443
32
+ DEFAULT_PROTOCOL = 'https'
33
+ REQUEST_TTL = 30
34
+ DEFAULT_VISIBILITY_TIMEOUT = 30
35
+
36
+
37
+ @@bench = AwsBenchmarkingBlock.new
38
+ def self.bench_xml
39
+ @@bench.xml
40
+ end
41
+ def self.bench_sqs
42
+ @@bench.service
43
+ end
44
+
45
+ @@api = API_VERSION
46
+ def self.api
47
+ @@api
48
+ end
49
+
50
+ # Creates a new SqsInterface instance.
51
+ #
52
+ # sqs = RightAws::SqsInterface.new('1E3GDYEOGFJPIT75KDT40','hgTHt68JY07JKUY08ftHYtERkjgtfERn57DFE379', {:multi_thread => true, :logger => Logger.new('/tmp/x.log')})
53
+ #
54
+ # Params is a hash:
55
+ #
56
+ # {:server => 'queue.amazonaws.com' # Amazon service host: 'queue.amazonaws.com'(default)
57
+ # :port => 443 # Amazon service port: 80 or 443(default)
58
+ # :multi_thread => true|false # Multi-threaded (connection per each thread): true or false(default)
59
+ # :signature_version => '0' # The signature version : '0' or '1'(default)
60
+ # :logger => Logger Object} # Logger instance: logs to STDOUT if omitted }
61
+ #
62
+ def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
63
+ init({ :name => 'SQS',
64
+ :default_host => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).host : DEFAULT_HOST,
65
+ :default_port => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).port : DEFAULT_PORT,
66
+ :default_protocol => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).scheme : DEFAULT_PROTOCOL },
67
+ aws_access_key_id || ENV['AWS_ACCESS_KEY_ID'],
68
+ aws_secret_access_key || ENV['AWS_SECRET_ACCESS_KEY'],
69
+ params)
70
+ end
71
+
72
+
73
+ #-----------------------------------------------------------------
74
+ # Requests
75
+ #-----------------------------------------------------------------
76
+
77
+ # Generates a request hash for the query API
78
+ def generate_request(action, params={}) # :nodoc:
79
+ # Sometimes we need to use queue uri (delete queue etc)
80
+ # In that case we will use Symbol key: 'param[:queue_url]'
81
+ service = params[:queue_url] ? URI(params[:queue_url]).path : '/'
82
+ # remove unset(=optional) and symbolyc keys
83
+ params.each{ |key, value| params.delete(key) if (value.nil? || key.is_a?(Symbol)) }
84
+ # prepare output hash
85
+ service_hash = { "Action" => action,
86
+ "Expires" => (Time.now + REQUEST_TTL).utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
87
+ "AWSAccessKeyId" => @aws_access_key_id,
88
+ "Version" => API_VERSION }
89
+ service_hash.update(params)
90
+ service_params = signed_service_params(@aws_secret_access_key, service_hash, :get, @params[:server], service)
91
+ request = Net::HTTP::Get.new("#{AwsUtils::URLencode(service)}?#{service_params}")
92
+ # prepare output hash
93
+ { :request => request,
94
+ :server => @params[:server],
95
+ :port => @params[:port],
96
+ :protocol => @params[:protocol] }
97
+ end
98
+
99
+ # Generates a request hash for the REST API
100
+ def generate_rest_request(method, param) # :nodoc:
101
+ queue_uri = param[:queue_url] ? URI(param[:queue_url]).path : '/'
102
+ message = param[:message] # extract message body if nesessary
103
+ # remove unset(=optional) and symbolyc keys
104
+ param.each{ |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
105
+ # created request
106
+ param_to_str = param.to_a.collect{|key,val| key.to_s + "=" + CGI::escape(val.to_s) }.join("&")
107
+ param_to_str = "?#{param_to_str}" unless param_to_str.blank?
108
+ request = "Net::HTTP::#{method.capitalize}".constantize.new("#{queue_uri}#{param_to_str}")
109
+ request.body = message if message
110
+ # set main headers
111
+ request['content-md5'] = ''
112
+ request['Content-Type'] = 'text/plain'
113
+ request['Date'] = Time.now.httpdate
114
+ # generate authorization string
115
+ auth_string = "#{method.upcase}\n#{request['content-md5']}\n#{request['Content-Type']}\n#{request['Date']}\n#{CGI::unescape(queue_uri)}"
116
+ signature = AwsUtils::sign(@aws_secret_access_key, auth_string)
117
+ # set other headers
118
+ request['Authorization'] = "AWS #{@aws_access_key_id}:#{signature}"
119
+ request['AWS-Version'] = API_VERSION
120
+ # prepare output hash
121
+ { :request => request,
122
+ :server => @params[:server],
123
+ :port => @params[:port],
124
+ :protocol => @params[:protocol] }
125
+ end
126
+
127
+
128
+ # Sends request to Amazon and parses the response
129
+ # Raises AwsError if any banana happened
130
+ def request_info(request, parser) # :nodoc:
131
+ thread = @params[:multi_thread] ? Thread.current : Thread.main
132
+ thread[:sqs_connection] ||= Rightscale::HttpConnection.new(:exception => AwsError, :logger => @logger)
133
+ request_info_impl(thread[:sqs_connection], @@bench, request, parser)
134
+ end
135
+
136
+
137
+ # Creates new queue. Returns new queue link.
138
+ #
139
+ # sqs.create_queue('my_awesome_queue') #=> 'http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
140
+ #
141
+ # PS Some queue based requests may not become available until a couple of minutes after queue creation
142
+ # (permission grant and removal for example)
143
+ #
144
+ def create_queue(queue_name, default_visibility_timeout=nil)
145
+ req_hash = generate_request('CreateQueue',
146
+ 'QueueName' => queue_name,
147
+ 'DefaultVisibilityTimeout' => default_visibility_timeout || DEFAULT_VISIBILITY_TIMEOUT )
148
+ request_info(req_hash, SqsCreateQueueParser.new(:logger => @logger))
149
+ end
150
+
151
+ # Lists all queues owned by this user that have names beginning with +queue_name_prefix+. If +queue_name_prefix+ is omitted then retrieves a list of all queues.
152
+ #
153
+ # sqs.create_queue('my_awesome_queue')
154
+ # sqs.create_queue('my_awesome_queue_2')
155
+ # sqs.list_queues('my_awesome') #=> ['http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue','http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2']
156
+ #
157
+ def list_queues(queue_name_prefix=nil)
158
+ req_hash = generate_request('ListQueues', 'QueueNamePrefix' => queue_name_prefix)
159
+ request_info(req_hash, SqsListQueuesParser.new(:logger => @logger))
160
+ rescue
161
+ on_exception
162
+ end
163
+
164
+ # Deletes queue (queue must be empty or +force_deletion+ must be set to true). Queue is identified by url. Returns +true+ or an exception.
165
+ #
166
+ # sqs.delete_queue('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2') #=> true
167
+ #
168
+ def delete_queue(queue_url, force_deletion = false)
169
+ req_hash = generate_request('DeleteQueue',
170
+ 'ForceDeletion' => force_deletion.to_s,
171
+ :queue_url => queue_url)
172
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
173
+ rescue
174
+ on_exception
175
+ end
176
+
177
+ # Retrieves the queue attribute(s). Returns a hash of attribute(s) or an exception.
178
+ #
179
+ # sqs.get_queue_attributes('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> {"ApproximateNumberOfMessages"=>"0", "VisibilityTimeout"=>"30"}
180
+ #
181
+ def get_queue_attributes(queue_url, attribute='All')
182
+ req_hash = generate_request('GetQueueAttributes',
183
+ 'Attribute' => attribute,
184
+ :queue_url => queue_url)
185
+ request_info(req_hash, SqsGetQueueAttributesParser.new(:logger => @logger))
186
+ rescue
187
+ on_exception
188
+ end
189
+
190
+ # Sets queue attribute. Returns +true+ or an exception.
191
+ #
192
+ # sqs.set_queue_attributes('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', "VisibilityTimeout", 10) #=> true
193
+ #
194
+ # P.S. Amazon returns success even if the attribute does not exist. Also, attribute values may not be immediately available to other queries
195
+ # for some time after an update (see the SQS documentation for
196
+ # semantics).
197
+ def set_queue_attributes(queue_url, attribute, value)
198
+ req_hash = generate_request('SetQueueAttributes',
199
+ 'Attribute' => attribute,
200
+ 'Value' => value,
201
+ :queue_url => queue_url)
202
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
203
+ rescue
204
+ on_exception
205
+ end
206
+
207
+ # Sets visibility timeout. Returns +true+ or an exception.
208
+ #
209
+ # sqs.set_visibility_timeout('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 15) #=> true
210
+ #
211
+ # See also: +set_queue_attributes+
212
+ #
213
+ def set_visibility_timeout(queue_url, visibility_timeout=nil)
214
+ req_hash = generate_request('SetVisibilityTimeout',
215
+ 'VisibilityTimeout' => visibility_timeout || DEFAULT_VISIBILITY_TIMEOUT,
216
+ :queue_url => queue_url )
217
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
218
+ rescue
219
+ on_exception
220
+ end
221
+
222
+ # Retrieves visibility timeout.
223
+ #
224
+ # sqs.get_visibility_timeout('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 15
225
+ #
226
+ # See also: +get_queue_attributes+
227
+ #
228
+ def get_visibility_timeout(queue_url)
229
+ req_hash = generate_request('GetVisibilityTimeout', :queue_url => queue_url )
230
+ request_info(req_hash, SqsGetVisibilityTimeoutParser.new(:logger => @logger))
231
+ rescue
232
+ on_exception
233
+ end
234
+
235
+ # Adds grants for user (identified by email he registered at Amazon). Returns +true+ or an exception. Permission = 'FULLCONTROL' | 'RECEIVEMESSAGE' | 'SENDMESSAGE'.
236
+ #
237
+ # sqs.add_grant('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'my_awesome_friend@gmail.com', 'FULLCONTROL') #=> true
238
+ #
239
+ def add_grant(queue_url, grantee_email_address, permission = nil)
240
+ req_hash = generate_request('AddGrant',
241
+ 'Grantee.EmailAddress' => grantee_email_address,
242
+ 'Permission' => permission,
243
+ :queue_url => queue_url)
244
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
245
+ rescue
246
+ on_exception
247
+ end
248
+
249
+ # Retrieves hash of +grantee_id+ => +perms+ for this queue:
250
+ #
251
+ # sqs.list_grants('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=>
252
+ # {"000000000000000000000001111111111117476c7fea6efb2c3347ac3ab2792a"=>{:name=>"root", :perms=>["FULLCONTROL"]},
253
+ # "00000000000000000000000111111111111e5828344600fc9e4a784a09e97041"=>{:name=>"myawesomefriend", :perms=>["FULLCONTROL"]}
254
+ #
255
+ def list_grants(queue_url, grantee_email_address=nil, permission = nil)
256
+ req_hash = generate_request('ListGrants',
257
+ 'Grantee.EmailAddress' => grantee_email_address,
258
+ 'Permission' => permission,
259
+ :queue_url => queue_url)
260
+ response = request_info(req_hash, SqsListGrantsParser.new(:logger => @logger))
261
+ # One user may have up to 3 permission records for every queue.
262
+ # We will join these records to one.
263
+ result = {}
264
+ response.each do |perm|
265
+ id = perm[:id]
266
+ # create hash for new user if unexisit
267
+ result[id] = {:perms=>[]} unless result[id]
268
+ # fill current grantee params
269
+ result[id][:perms] << perm[:permission]
270
+ result[id][:name] = perm[:name]
271
+ end
272
+ result
273
+ end
274
+
275
+ # Revokes permission from user. Returns +true+ or an exception.
276
+ #
277
+ # sqs.remove_grant('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'my_awesome_friend@gmail.com', 'FULLCONTROL') #=> true
278
+ #
279
+ def remove_grant(queue_url, grantee_email_address_or_id, permission = nil)
280
+ grantee_key = grantee_email_address_or_id.include?('@') ? 'Grantee.EmailAddress' : 'Grantee.ID'
281
+ req_hash = generate_request('RemoveGrant',
282
+ grantee_key => grantee_email_address_or_id,
283
+ 'Permission' => permission,
284
+ :queue_url => queue_url)
285
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
286
+ rescue
287
+ on_exception
288
+ end
289
+
290
+ # Retrieves a list of messages from queue. Returns an array of hashes in format: <tt>{:id=>'message_id', body=>'message_body'}</tt>
291
+ #
292
+ # sqs.receive_messages('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',10, 5) #=>
293
+ # [{:id=>"12345678904GEZX9746N|0N9ED344VK5Z3SV1DTM0|1RVYH4X3TJ0987654321", :body=>"message_1"}, ..., {}]
294
+ #
295
+ # P.S. Usually returns fewer messages than requested even if they are available.
296
+ #
297
+ def receive_messages(queue_url, number_of_messages=1, visibility_timeout=nil)
298
+ return [] if number_of_messages == 0
299
+ req_hash = generate_rest_request('GET',
300
+ 'NumberOfMessages' => number_of_messages,
301
+ 'VisibilityTimeout' => visibility_timeout,
302
+ :queue_url => "#{queue_url}/front" )
303
+ request_info(req_hash, SqsReceiveMessagesParser.new(:logger => @logger))
304
+ rescue
305
+ on_exception
306
+ end
307
+
308
+ # Peeks message from queue by message id. Returns message in format of <tt>{:id=>'message_id', :body=>'message_body'}</tt> or +nil+.
309
+ #
310
+ # sqs.peek_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', '1234567890...0987654321') #=>
311
+ # {:id=>"12345678904GEZX9746N|0N9ED344VK5Z3SV1DTM0|1RVYH4X3TJ0987654321", :body=>"message_1"}
312
+ #
313
+ def peek_message(queue_url, message_id)
314
+ req_hash = generate_rest_request('GET', :queue_url => "#{queue_url}/#{CGI::escape message_id}" )
315
+ messages = request_info(req_hash, SqsReceiveMessagesParser.new(:logger => @logger))
316
+ messages.blank? ? nil : messages[0]
317
+ rescue
318
+ on_exception
319
+ end
320
+
321
+ # Sends new message to queue.Returns 'message_id' or raises an exception.
322
+ #
323
+ # sqs.send_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'message_1') #=> "1234567890...0987654321"
324
+ #
325
+ def send_message(queue_url, message)
326
+ req_hash = generate_rest_request('PUT',
327
+ :message => message,
328
+ :queue_url => "#{queue_url}/back")
329
+ request_info(req_hash, SqsSendMessagesParser.new(:logger => @logger))
330
+ rescue
331
+ on_exception
332
+ end
333
+
334
+ # Deletes message from queue. Returns +true+ or an exception. Amazon
335
+ # returns +true+ on deletion of non-existent messages.
336
+ #
337
+ # sqs.delete_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', '12345678904...0987654321') #=> true
338
+ #
339
+ def delete_message(queue_url, message_id)
340
+ req_hash = generate_request('DeleteMessage',
341
+ 'MessageId' => message_id,
342
+ :queue_url => queue_url)
343
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
344
+ rescue
345
+ on_exception
346
+ end
347
+
348
+ # Changes message visibility timeout. Returns +true+ or an exception.
349
+ #
350
+ # sqs.change_message_visibility('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', '1234567890...0987654321', 10) #=> true
351
+ #
352
+ def change_message_visibility(queue_url, message_id, visibility_timeout=0)
353
+ req_hash = generate_request('ChangeMessageVisibility',
354
+ 'MessageId' => message_id,
355
+ 'VisibilityTimeout' => visibility_timeout.to_s,
356
+ :queue_url => queue_url)
357
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
358
+ rescue
359
+ on_exception
360
+ end
361
+
362
+ # Returns queue url by queue short name or +nil+ if queue is not found
363
+ #
364
+ # sqs.queue_url_by_name('my_awesome_queue') #=> 'http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
365
+ #
366
+ def queue_url_by_name(queue_name)
367
+ return queue_name if queue_name.include?('/')
368
+ queue_urls = list_queues(queue_name)
369
+ queue_urls.each do |queue_url|
370
+ return queue_url if queue_name_by_url(queue_url) == queue_name
371
+ end
372
+ nil
373
+ rescue
374
+ on_exception
375
+ end
376
+
377
+ # Returns short queue name by url.
378
+ #
379
+ # RightSqs.queue_name_by_url('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
380
+ #
381
+ def self.queue_name_by_url(queue_url)
382
+ queue_url[/[^\/]*$/]
383
+ rescue
384
+ on_exception
385
+ end
386
+
387
+ # Returns short queue name by url.
388
+ #
389
+ # sqs.queue_name_by_url('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
390
+ #
391
+ def queue_name_by_url(queue_url)
392
+ self.class.queue_name_by_url(queue_url)
393
+ rescue
394
+ on_exception
395
+ end
396
+
397
+ # Returns approximate number of messages in queue.
398
+ #
399
+ # sqs.get_queue_length('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 3
400
+ #
401
+ def get_queue_length(queue_url)
402
+ get_queue_attributes(queue_url)['ApproximateNumberOfMessages'].to_i
403
+ rescue
404
+ on_exception
405
+ end
406
+
407
+ # Removes all visible messages from queue. Return +true+ or an exception.
408
+ #
409
+ # sqs.clear_queue('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> true
410
+ #
411
+ def clear_queue(queue_url)
412
+ while (m = pop_message(queue_url)) ; end # delete all messages in queue
413
+ true
414
+ rescue
415
+ on_exception
416
+ end
417
+
418
+ # Deletes queue then re-creates it (restores attributes also). The fastest method to clear big queue or queue with invisible messages. Return +true+ or an exception.
419
+ #
420
+ # sqs.force_clear_queue('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> true
421
+ #
422
+ # PS This function is no longer supported. Amazon has changed the SQS semantics to require at least 60 seconds between
423
+ # queue deletion and creation. Hence this method will fail with an exception.
424
+ #
425
+ def force_clear_queue(queue_url)
426
+ queue_name = queue_name_by_url(queue_url)
427
+ queue_attributes = get_queue_attributes(queue_url)
428
+ force_delete_queue(queue_url)
429
+ create_queue(queue_name)
430
+ # hmmm... The next line is a trick. Amazon do not want change attributes immediately after queue creation
431
+ # So we do 'empty' get_queue_attributes. Probably they need some time to allow attributes change.
432
+ get_queue_attributes(queue_url)
433
+ queue_attributes.each{ |attribute, value| set_queue_attributes(queue_url, attribute, value) }
434
+ true
435
+ rescue
436
+ on_exception
437
+ end
438
+
439
+ # Deletes queue even if it has messages. Return +true+ or an exception.
440
+ #
441
+ # force_delete_queue('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> true
442
+ #
443
+ # P.S. same as <tt>delete_queue('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', true)</tt>
444
+ def force_delete_queue(queue_url)
445
+ delete_queue(queue_url, true)
446
+ rescue
447
+ on_exception
448
+ end
449
+
450
+ # Reads first accessible message from queue. Returns message as a hash: <tt>{:id=>'message_id', :body=>'message_body'}</tt> or +nil+.
451
+ #
452
+ # sqs.receive_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 10) #=>
453
+ # {:id=>"12345678904GEZX9746N|0N9ED344VK5Z3SV1DTM0|1RVYH4X3TJ0987654321", :body=>"message_1"}
454
+ #
455
+ def receive_message(queue_url, visibility_timeout=nil)
456
+ result = receive_messages(queue_url, 1, visibility_timeout)
457
+ result.blank? ? nil : result[0]
458
+ rescue
459
+ on_exception
460
+ end
461
+
462
+ # Same as send_message
463
+ alias_method :push_message, :send_message
464
+
465
+ # 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>.
466
+ #
467
+ # sqs.pop_messages('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 3) #=>
468
+ # [{:id=>"12345678904GEZX9746N|0N9ED344VK5Z3SV1DTM0|1RVYH4X3TJ0987654321", :body=>"message_1"}, ..., {}]
469
+ #
470
+ def pop_messages(queue_url, number_of_messages=1)
471
+ messages = receive_messages(queue_url, number_of_messages)
472
+ messages.each do |message|
473
+ delete_message(queue_url, message[:id])
474
+ end
475
+ messages
476
+ rescue
477
+ on_exception
478
+ end
479
+
480
+ # Pops (retrieves and deletes) first accessible message from queue. Returns the message in format <tt>{:id=>'message_id', :body=>'message_body'}</tt> or +nil+.
481
+ #
482
+ # sqs.pop_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=>
483
+ # {:id=>"12345678904GEZX9746N|0N9ED344VK5Z3SV1DTM0|1RVYH4X3TJ0987654321", :body=>"message_1"}
484
+ #
485
+ def pop_message(queue_url)
486
+ messages = pop_messages(queue_url)
487
+ messages.blank? ? nil : messages[0]
488
+ rescue
489
+ on_exception
490
+ end
491
+
492
+ #-----------------------------------------------------------------
493
+ # PARSERS: Status Response Parser
494
+ #-----------------------------------------------------------------
495
+
496
+ class SqsStatusParser < RightAWSParser # :nodoc:
497
+ def tagend(name)
498
+ if name == 'StatusCode'
499
+ @result = @text=='Success' ? true : false
500
+ end
501
+ end
502
+ end
503
+
504
+ #-----------------------------------------------------------------
505
+ # PARSERS: Queue
506
+ #-----------------------------------------------------------------
507
+
508
+ class SqsCreateQueueParser < RightAWSParser # :nodoc:
509
+ def tagend(name)
510
+ @result = @text if name == 'QueueUrl'
511
+ end
512
+ end
513
+
514
+ class SqsListQueuesParser < RightAWSParser # :nodoc:
515
+ def reset
516
+ @result = []
517
+ end
518
+ def tagend(name)
519
+ @result << @text if name == 'QueueUrl'
520
+ end
521
+ end
522
+
523
+ class SqsGetQueueAttributesParser < RightAWSParser # :nodoc:
524
+ def reset
525
+ @result = {}
526
+ end
527
+ def tagend(name)
528
+ case name
529
+ when 'Attribute' ; @current_attribute = @text
530
+ when 'Value' ; @result[@current_attribute] = @text
531
+ # when 'StatusCode'; @result['status_code'] = @text
532
+ # when 'RequestId' ; @result['request_id'] = @text
533
+ end
534
+ end
535
+ end
536
+
537
+ #-----------------------------------------------------------------
538
+ # PARSERS: Timeouts
539
+ #-----------------------------------------------------------------
540
+
541
+ class SqsGetVisibilityTimeoutParser < RightAWSParser # :nodoc:
542
+ def tagend(name)
543
+ @result = @text.to_i if name == 'VisibilityTimeout'
544
+ end
545
+ end
546
+
547
+ #-----------------------------------------------------------------
548
+ # PARSERS: Permissions
549
+ #-----------------------------------------------------------------
550
+
551
+ class SqsListGrantsParser < RightAWSParser # :nodoc:
552
+ def reset
553
+ @result = []
554
+ end
555
+ def tagstart(name, attributes)
556
+ @current_perms = {} if name == 'GrantList'
557
+ end
558
+ def tagend(name)
559
+ case name
560
+ when 'ID' ; @current_perms[:id] = @text
561
+ when 'DisplayName'; @current_perms[:name] = @text
562
+ when 'Permission' ; @current_perms[:permission] = @text
563
+ when 'GrantList' ; @result << @current_perms
564
+ end
565
+ end
566
+ end
567
+
568
+ #-----------------------------------------------------------------
569
+ # PARSERS: Messages
570
+ #-----------------------------------------------------------------
571
+
572
+ class SqsReceiveMessagesParser < RightAWSParser # :nodoc:
573
+ def reset
574
+ @result = []
575
+ end
576
+ def tagstart(name, attributes)
577
+ @current_message = {} if name == 'Message'
578
+ end
579
+ def tagend(name)
580
+ case name
581
+ when 'MessageId' ; @current_message[:id] = @text
582
+ when 'MessageBody'; @current_message[:body] = @text
583
+ when 'Message' ; @result << @current_message
584
+ end
585
+ end
586
+ end
587
+
588
+ class SqsSendMessagesParser < RightAWSParser # :nodoc:
589
+ def tagend(name)
590
+ @result = @text if name == 'MessageId'
591
+ end
592
+ end
593
+
594
+ end
595
+
596
+ end