aws 2.3.34 → 2.4.0

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