kerryb-right_aws 1.7.3

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