aws 2.3.34 → 2.4.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -279,6 +279,16 @@ module Aws
279
279
  def delete
280
280
  @queue.sqs.interface.delete_message(@queue.url, @receipt_handle) if @receipt_handle
281
281
  end
282
+
283
+ # Updates visibility timeout.
284
+ def visibility=(visibility_timeout)
285
+ if @receipt_handle
286
+ @queue.sqs.interface.change_message_visibility(
287
+ @queue.url, @receipt_handle, visibility_timeout
288
+ )
289
+ @visibility = visibility_timeout
290
+ end
291
+ end
282
292
 
283
293
  end
284
294
 
@@ -0,0 +1,483 @@
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
+ def self.connection_name
50
+ :sqs_connection
51
+ end
52
+
53
+ @@bench = AwsBenchmarkingBlock.new
54
+
55
+ def self.bench
56
+ @@bench
57
+ end
58
+
59
+ def self.bench_xml
60
+ @@bench.xml
61
+ end
62
+
63
+ def self.bench_sqs
64
+ @@bench.service
65
+ end
66
+
67
+ @@api = API_VERSION
68
+
69
+ def self.api
70
+ @@api
71
+ end
72
+
73
+ # Creates a new SqsInterface instance. This instance is limited to
74
+ # operations on SQS objects created with Amazon's 2008-01-01 API version. This
75
+ # interface will not work on objects created with prior API versions. See
76
+ # Amazon's article "Migrating to Amazon SQS API version 2008-01-01" at:
77
+ # http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1148
78
+ #
79
+ # sqs = Aws::SqsInterface.new('1E3GDYEOGFJPIT75KDT40','hgTHt68JY07JKUY08ftHYtERkjgtfERn57DFE379', {:multi_thread => true, :logger => Logger.new('/tmp/x.log')})
80
+ #
81
+ # Params is a hash:
82
+ #
83
+ # {:server => 'queue.amazonaws.com' # Amazon service host: 'queue.amazonaws.com' (default)
84
+ # :port => 443 # Amazon service port: 80 or 443 (default)
85
+ # :multi_thread => true|false # Multi-threaded (connection per each thread): true or false (default)
86
+ # :signature_version => '0' # The signature version : '0' or '1'(default)
87
+ # :logger => Logger Object} # Logger instance: logs to STDOUT if omitted }
88
+ #
89
+ def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
90
+ init({:name => 'SQS',
91
+ :default_host => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).host : DEFAULT_HOST,
92
+ :default_port => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).port : DEFAULT_PORT,
93
+ :default_protocol => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).scheme : DEFAULT_PROTOCOL,
94
+ :api_version => API_VERSION},
95
+ aws_access_key_id || ENV['AWS_ACCESS_KEY_ID'],
96
+ aws_secret_access_key || ENV['AWS_SECRET_ACCESS_KEY'],
97
+ params)
98
+ end
99
+
100
+
101
+ #-----------------------------------------------------------------
102
+ # Requests
103
+ #-----------------------------------------------------------------
104
+
105
+ # Generates a request hash for the query API
106
+ def generate_request(action, param={}) # :nodoc:
107
+ # For operation requests on a queue, the queue URI will be a parameter,
108
+ # so we first extract it from the call parameters. Next we remove any
109
+ # parameters with no value or with symbolic keys. We add the header
110
+ # fields required in all requests, and then the headers passed in as
111
+ # params. We sort the header fields alphabetically and then generate the
112
+ # signature before URL escaping the resulting query and sending it.
113
+ service = param[:queue_url] ? URI(param[:queue_url]).path : '/'
114
+ param.each { |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
115
+ service_hash = {"Action" => action,
116
+ "Expires" => (Time.now + REQUEST_TTL).utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
117
+ "AWSAccessKeyId" => @aws_access_key_id,
118
+ "Version" => API_VERSION}
119
+ service_hash.update(param)
120
+ service_params = signed_service_params(@aws_secret_access_key, service_hash, :get, @params[:server], service)
121
+ request = Net::HTTP::Get.new("#{AwsUtils.URLencode(service)}?#{service_params}")
122
+ # prepare output hash
123
+ {:request => request,
124
+ :server => @params[:server],
125
+ :port => @params[:port],
126
+ :protocol => @params[:protocol]}
127
+ end
128
+
129
+ def generate_post_request(action, param={}) # :nodoc:
130
+ service = param[:queue_url] ? URI(param[:queue_url]).path : '/'
131
+ message = param[:message] # extract message body if nesessary
132
+ param.each { |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
133
+ service_hash = {"Action" => action,
134
+ "Expires" => (Time.now + REQUEST_TTL).utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
135
+ "AWSAccessKeyId" => @aws_access_key_id,
136
+ "MessageBody" => message,
137
+ "Version" => API_VERSION}
138
+ service_hash.update(param)
139
+ #
140
+ service_params = signed_service_params(@aws_secret_access_key, service_hash, :post, @params[:server], service)
141
+ request = Net::HTTP::Post.new(AwsUtils::URLencode(service))
142
+ request['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
143
+ request.body = service_params
144
+ # prepare output hash
145
+ {:request => request,
146
+ :server => @params[:server],
147
+ :port => @params[:port],
148
+ :protocol => @params[:protocol]}
149
+ end
150
+
151
+
152
+ # Sends request to Amazon and parses the response
153
+ # Raises AwsError if any banana happened
154
+ # todo: remove this and switch to using request_info2
155
+ def request_info(request, parser, options={}) # :nodoc:
156
+ conn = get_conn(self.class.connection_name, @params, @logger)
157
+ request_info_impl(conn, @@bench, request, parser, options)
158
+ end
159
+
160
+ # Creates a new queue, returning its URI.
161
+ #
162
+ # sqs.create_queue('my_awesome_queue') #=> 'http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
163
+ #
164
+ def create_queue(queue_name, default_visibility_timeout=nil)
165
+ req_hash = generate_request('CreateQueue', 'QueueName' => queue_name,
166
+ 'DefaultVisibilityTimeout' => default_visibility_timeout || DEFAULT_VISIBILITY_TIMEOUT)
167
+ request_info(req_hash, SqsCreateQueueParser.new(:logger => @logger))
168
+ rescue
169
+ on_exception
170
+ end
171
+
172
+ # Lists all queues owned by this user that have names beginning with +queue_name_prefix+.
173
+ # If +queue_name_prefix+ is omitted then retrieves a list of all queues.
174
+ # Queue creation is an eventual operation and created queues may not show up in immediately subsequent list_queues calls.
175
+ #
176
+ # sqs.create_queue('my_awesome_queue')
177
+ # sqs.create_queue('my_awesome_queue_2')
178
+ # sqs.list_queues('my_awesome') #=> ['http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue','http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2']
179
+ #
180
+ def list_queues(queue_name_prefix=nil)
181
+ req_hash = generate_request('ListQueues', 'QueueNamePrefix' => queue_name_prefix)
182
+ request_info(req_hash, SqsListQueuesParser.new(:logger => @logger))
183
+ rescue
184
+ on_exception
185
+ end
186
+
187
+ # Deletes queue. Any messages in the queue are permanently lost.
188
+ # Returns +true+ or an exception.
189
+ # Queue deletion can take up to 60 s to propagate through SQS. Thus, after a deletion, subsequent list_queues calls
190
+ # may still show the deleted queue. It is not unusual within the 60 s window to see the deleted queue absent from
191
+ # one list_queues call but present in the subsequent one. Deletion is eventual.
192
+ #
193
+ # sqs.delete_queue('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2') #=> true
194
+ #
195
+ #
196
+ def delete_queue(queue_url)
197
+ req_hash = generate_request('DeleteQueue', :queue_url => queue_url)
198
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
199
+ rescue
200
+ on_exception
201
+ end
202
+
203
+ # Retrieves the queue attribute(s). Returns a hash of attribute(s) or an exception.
204
+ #
205
+ # sqs.get_queue_attributes('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue')
206
+ # #=> {"ApproximateNumberOfMessages"=>"0", "VisibilityTimeout"=>"30"}
207
+ #
208
+ def get_queue_attributes(queue_url, attribute='All')
209
+ req_hash = generate_request('GetQueueAttributes', 'AttributeName' => attribute, :queue_url => queue_url)
210
+ request_info(req_hash, SqsGetQueueAttributesParser.new(:logger => @logger))
211
+ rescue
212
+ on_exception
213
+ end
214
+
215
+ # Sets queue attribute. Returns +true+ or an exception.
216
+ #
217
+ # sqs.set_queue_attributes('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', "VisibilityTimeout", 10) #=> true
218
+ #
219
+ # From the SQS Dev Guide:
220
+ # "Currently, you can set only the
221
+ # VisibilityTimeout attribute for a queue...
222
+ # When you change a queue's attributes, the change can take up to 60 seconds to propagate
223
+ # throughout the SQS system."
224
+ #
225
+ # NB: Attribute values may not be immediately available to other queries
226
+ # for some time after an update. See the SQS documentation for
227
+ # semantics, but in general propagation can take up to 60 s.
228
+ def set_queue_attributes(queue_url, attribute, value)
229
+ req_hash = generate_request('SetQueueAttributes', 'Attribute.Name' => attribute, 'Attribute.Value' => value, :queue_url => queue_url)
230
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
231
+ rescue
232
+ on_exception
233
+ end
234
+
235
+ # Retrieves a list of messages from queue. Returns an array of hashes in format: <tt>{:id=>'message_id', body=>'message_body'}</tt>
236
+ #
237
+ # sqs.receive_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',10, 5) #=>
238
+ # [{"ReceiptHandle"=>"Euvo62...kw==", "MD5OfBody"=>"16af2171b5b83cfa35ce254966ba81e3",
239
+ # "Body"=>"Goodbyte World!", "MessageId"=>"MUM4WlAyR...pYOTA="}, ..., {}]
240
+ #
241
+ # Normally this call returns fewer messages than the maximum specified,
242
+ # even if they are available.
243
+ #
244
+ def receive_message(queue_url, max_number_of_messages=1, visibility_timeout=nil)
245
+ return [] if max_number_of_messages == 0
246
+ req_hash = generate_post_request('ReceiveMessage', 'MaxNumberOfMessages' => max_number_of_messages, 'VisibilityTimeout' => visibility_timeout,
247
+ :queue_url => queue_url)
248
+ request_info(req_hash, SqsReceiveMessageParser.new(:logger => @logger))
249
+ rescue
250
+ on_exception
251
+ end
252
+
253
+ # Sends a new message to a queue. Message size is limited to 8 KB.
254
+ # If successful, this call returns a hash containing key/value pairs for
255
+ # "MessageId" and "MD5OfMessageBody":
256
+ #
257
+ # sqs.send_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'message_1') #=> "1234567890...0987654321"
258
+ # => {"MessageId"=>"MEs4M0JKNlRCRTBBSENaMjROTk58QVFRNzNEREhDVFlFOVJDQ1JKNjF8UTdBRllCUlJUMjhKMUI1WDJSWDE=", "MD5OfMessageBody"=>"16af2171b5b83cfa35ce254966ba81e3"}
259
+ #
260
+ # On failure, send_message raises an exception.
261
+ #
262
+ #
263
+ def send_message(queue_url, message)
264
+ req_hash = generate_post_request('SendMessage', :message => message, :queue_url => queue_url)
265
+ request_info(req_hash, SqsSendMessagesParser.new(:logger => @logger))
266
+ rescue
267
+ on_exception
268
+ end
269
+
270
+ # Same as send_message
271
+ alias_method :push_message, :send_message
272
+
273
+
274
+ # Deletes message from queue. Returns +true+ or an exception. Amazon
275
+ # returns +true+ on deletion of non-existent messages. You must use the
276
+ # receipt handle for a message to delete it, not the message ID.
277
+ #
278
+ # From the SQS Developer Guide:
279
+ # "It is possible you will receive a message even after you have deleted it. This might happen
280
+ # on rare occasions if one of the servers storing a copy of the message is unavailable when
281
+ # you request to delete the message. The copy remains on the server and might be returned to
282
+ # you again on a subsequent receive request. You should create your system to be
283
+ # idempotent so that receiving a particular message more than once is not a problem. "
284
+ #
285
+ # sqs.delete_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'Euvo62/1nlIet...ao03hd9Sa0w==') #=> true
286
+ #
287
+ def delete_message(queue_url, receipt_handle)
288
+ req_hash = generate_request('DeleteMessage', 'ReceiptHandle' => receipt_handle, :queue_url => queue_url)
289
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
290
+ rescue
291
+ on_exception
292
+ end
293
+
294
+ # Sets new visibility timeout value for a message identified by "receipt_handle"
295
+ # Check out the Amazon SQS API documentation for further details.
296
+ def change_message_visibility(queue_url, receipt_handle, visibility_timeout)
297
+ req_hash = generate_request(
298
+ "ChangeMessageVisibility",
299
+ "ReceiptHandle" => receipt_handle,
300
+ "VisibilityTimeout" => visibility_timeout,
301
+ :queue_url => queue_url
302
+ )
303
+ request_info(req_hash, SqsStatusParser.new(:logger => @logger))
304
+ rescue
305
+ on_exception
306
+ end
307
+
308
+ # Given the queue's short name, this call returns the queue URL or +nil+ if queue is not found
309
+ # sqs.queue_url_by_name('my_awesome_queue') #=> 'http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'
310
+ #
311
+ def queue_url_by_name(queue_name)
312
+ return queue_name if queue_name.include?('/')
313
+ queue_urls = list_queues(queue_name)
314
+ queue_urls.each do |queue_url|
315
+ return queue_url if queue_name_by_url(queue_url) == queue_name
316
+ end
317
+ nil
318
+ rescue
319
+ on_exception
320
+ end
321
+
322
+ # Returns short queue name by url.
323
+ #
324
+ # RightSqs.queue_name_by_url('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
325
+ #
326
+ def self.queue_name_by_url(queue_url)
327
+ queue_url[/[^\/]*$/]
328
+ rescue
329
+ on_exception
330
+ end
331
+
332
+ # Returns short queue name by url.
333
+ #
334
+ # sqs.queue_name_by_url('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'
335
+ #
336
+ def queue_name_by_url(queue_url)
337
+ self.class.queue_name_by_url(queue_url)
338
+ rescue
339
+ on_exception
340
+ end
341
+
342
+ # Returns approximate number of messages in queue.
343
+ #
344
+ # sqs.get_queue_length('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 3
345
+ #
346
+ def get_queue_length(queue_url)
347
+ get_queue_attributes(queue_url)['ApproximateNumberOfMessages'].to_i
348
+ rescue
349
+ on_exception
350
+ end
351
+
352
+ # Removes all visible messages from queue. Return +true+ or an exception.
353
+ #
354
+ # sqs.clear_queue('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> true
355
+ #
356
+ def clear_queue(queue_url)
357
+ while (pop_messages(queue_url, 10).length > 0);
358
+ end # delete all messages in queue
359
+ true
360
+ rescue
361
+ on_exception
362
+ end
363
+
364
+ # 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>.
365
+ #
366
+ # sqs.pop_messages('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 3) #=>
367
+ # [{"ReceiptHandle"=>"Euvo62/...+Zw==", "MD5OfBody"=>"16af2...81e3", "Body"=>"Goodbyte World!",
368
+ # "MessageId"=>"MEZI...JSWDE="}, {...}, ... , {...} ]
369
+ #
370
+ def pop_messages(queue_url, number_of_messages=1)
371
+ messages = receive_message(queue_url, number_of_messages)
372
+ messages.each do |message|
373
+ delete_message(queue_url, message['ReceiptHandle'])
374
+ end
375
+ messages
376
+ rescue
377
+ on_exception
378
+ end
379
+
380
+ # Pops (retrieves and deletes) first accessible message from queue. Returns the message in format <tt>{:id=>'message_id', :body=>'message_body'}</tt> or +nil+.
381
+ #
382
+ # sqs.pop_message('http://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=>
383
+ # {:id=>"12345678904GEZX9746N|0N9ED344VK5Z3SV1DTM0|1RVYH4X3TJ0987654321", :body=>"message_1"}
384
+ #
385
+ def pop_message(queue_url)
386
+ messages = pop_messages(queue_url)
387
+ messages.blank? ? nil : messages[0]
388
+ rescue
389
+ on_exception
390
+ end
391
+
392
+ #-----------------------------------------------------------------
393
+ # PARSERS: Status Response Parser
394
+ #-----------------------------------------------------------------
395
+
396
+ class SqsStatusParser < AwsParser # :nodoc:
397
+ def tagend(name)
398
+ if name == 'ResponseMetadata'
399
+ @result = true
400
+ end
401
+ end
402
+ end
403
+
404
+ #-----------------------------------------------------------------
405
+ # PARSERS: Queue
406
+ #-----------------------------------------------------------------
407
+
408
+ class SqsCreateQueueParser < AwsParser # :nodoc:
409
+ def tagend(name)
410
+ @result = @text if name == 'QueueUrl'
411
+ end
412
+ end
413
+
414
+ class SqsListQueuesParser < AwsParser # :nodoc:
415
+ def reset
416
+ @result = []
417
+ end
418
+
419
+ def tagend(name)
420
+ @result << @text if name == 'QueueUrl'
421
+ end
422
+ end
423
+
424
+ class SqsGetQueueAttributesParser < AwsParser # :nodoc:
425
+ def reset
426
+ @result = {}
427
+ end
428
+
429
+ def tagend(name)
430
+ case name
431
+ when 'Name';
432
+ @current_attribute = @text
433
+ when 'Value';
434
+ @result[@current_attribute] = @text
435
+ end
436
+ end
437
+ end
438
+
439
+ #-----------------------------------------------------------------
440
+ # PARSERS: Messages
441
+ #-----------------------------------------------------------------
442
+
443
+ class SqsReceiveMessageParser < AwsParser # :nodoc:
444
+ def reset
445
+ @result = []
446
+ end
447
+
448
+ def tagstart(name, attributes)
449
+ @current_message = {} if name == 'Message'
450
+ end
451
+
452
+ def tagend(name)
453
+ case name
454
+ when 'MessageId';
455
+ @current_message['MessageId'] = @text
456
+ when 'ReceiptHandle';
457
+ @current_message['ReceiptHandle'] = @text
458
+ when 'MD5OfBody';
459
+ @current_message['MD5OfBody'] = @text
460
+ when 'Body';
461
+ @current_message['Body'] = @text; @result << @current_message
462
+ end
463
+ end
464
+ end
465
+
466
+ class SqsSendMessagesParser < AwsParser # :nodoc:
467
+ def reset
468
+ @result = {}
469
+ end
470
+
471
+ def tagend(name)
472
+ case name
473
+ when 'MessageId';
474
+ @result['MessageId'] = @text
475
+ when 'MD5OfMessageBody';
476
+ @result['MD5OfMessageBody'] = @text
477
+ end
478
+ end
479
+ end
480
+
481
+ end
482
+
483
+ end