Class: RightAws::SqsGen2Interface

Inherits:
RightAwsBase show all
Includes:
RightAwsBaseInterface
Defined in:
lib/sqs/right_sqs_gen2_interface.rb

Overview

Right::Aws::SqsGen2Interface - RightScale’s low-level Amazon SQS interface for API version 2008-01-01 and later. For explanations of the semantics of each call, please refer to Amazon’s documentation at developer.amazonwebservices.com/connect/kbcategory.jspa?categoryID=31

This class provides a procedural interface to SQS. Conceptually it is mostly a pass-through interface to SQS and its API is very similar to the bare SQS API. For a somewhat higher-level and object-oriented interface, see RightAws::SqsGen2.

Defined Under Namespace

Classes: SqsCreateQueueParser, SqsGetQueueAttributesParser, SqsListQueuesParser, SqsReceiveMessageParser, SqsSendMessagesParser, SqsStatusParser

Constant Summary collapse

API_VERSION =
"2009-02-01"
DEFAULT_HOST =
"queue.amazonaws.com"
DEFAULT_PORT =
443
DEFAULT_PROTOCOL =
'https'
REQUEST_TTL =
30
DEFAULT_VISIBILITY_TIMEOUT =
30
@@bench =
AwsBenchmarkingBlock.new
@@api =
API_VERSION

Constants included from RightAwsBaseInterface

RightAwsBaseInterface::BLOCK_DEVICE_KEY_MAPPING, RightAwsBaseInterface::DEFAULT_SIGNATURE_VERSION

Constants inherited from RightAwsBase

RightAwsBase::AMAZON_PROBLEMS, RightAwsBase::RAISE_ON_TIMEOUT_ON_ACTIONS

Instance Attribute Summary

Attributes included from RightAwsBaseInterface

#aws_access_key_id, #aws_secret_access_key, #cache, #connection, #last_errors, #last_request, #last_request_id, #last_response, #logger, #params, #signature_version

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RightAwsBaseInterface

#amazonize_block_device_mappings, #amazonize_list, #cache_hits?, caching, caching=, #caching?, #destroy_connection, #generate_request_impl, #get_connection, #get_connections_storage, #get_server_url, #incrementally_list_items, #init, #on_exception, #request_cache_or_info, #request_info_impl, #signed_service_params, #update_cache, #with_connection_options

Methods inherited from RightAwsBase

amazon_problems, amazon_problems=, raise_on_timeout_on_actions, raise_on_timeout_on_actions=

Constructor Details

#initialize(aws_access_key_id = nil, aws_secret_access_key = nil, params = {}) ⇒ SqsGen2Interface

Creates a new SqsInterface instance. This instance is limited to operations on SQS objects created with Amazon’s 2008-01-01 API version. This interface will not work on objects created with prior API versions. See Amazon’s article “Migrating to Amazon SQS API version 2008-01-01” at: developer.amazonwebservices.com/connect/entry.jspa?externalID=1148

sqs = RightAws::SqsGen2Interface.new('1E3GDYEOGFJPIT75KDT40','hgTHt68JY07JKUY08ftHYtERkjgtfERn57DFE379', {:logger => Logger.new('/tmp/x.log')})

Params is a hash:

{:server       => 'queue.amazonaws.com' # Amazon service host: 'queue.amazonaws.com' (default)
 :port         => 443                   # Amazon service port: 80 or 443 (default)
 :signature_version => '0'              # The signature version : '0', '1' or '2'(default)
 :logger       => Logger Object}        # Logger instance: logs to STDOUT if omitted }


77
78
79
80
81
82
83
84
85
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 77

def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
  init({ :name             => 'SQS', 
         :default_host     => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).host   : DEFAULT_HOST, 
         :default_port     => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).port   : DEFAULT_PORT, 
         :default_protocol => ENV['SQS_URL'] ? URI.parse(ENV['SQS_URL']).scheme : DEFAULT_PROTOCOL }, 
       aws_access_key_id     || ENV['AWS_ACCESS_KEY_ID'], 
       aws_secret_access_key || ENV['AWS_SECRET_ACCESS_KEY'], 
       params)
end

Class Method Details

.apiObject



58
59
60
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 58

def self.api 
  @@api
end

.bench_sqsObject



53
54
55
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 53

def self.bench_sqs
  @@bench.service
end

.bench_xmlObject



50
51
52
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 50

def self.bench_xml
  @@bench.xml
end

.queue_name_by_url(queue_url) ⇒ Object

Returns short queue name by url.

RightSqs.queue_name_by_url('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'


369
370
371
372
373
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 369

def self.queue_name_by_url(queue_url)
  queue_url[/[^\/]*$/]
rescue
  on_exception
end

Instance Method Details

#add_permissions(queue_url, label, grantees, actions) ⇒ Object

Add permissions to a queue.

sqs.add_permissions('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',
                   'testLabel', ['125074342641','125074342642'],
                   ['SendMessage','SendMessage','ReceiveMessage']) #=> true

+permissions+ is a hash of: AccountId => ActionName
(valid ActionNames: * | SendMessage | ReceiveMessage | DeleteMessage | ChangeMessageVisibility | GetQueueAttributes )

see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryAddPermission.html
    http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?acp-overview.html


246
247
248
249
250
251
252
253
254
255
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 246

def add_permissions(queue_url, label, grantees, actions)
  params      = amazonize_list('AWSAccountId', Array(grantees))
  params.merge!(amazonize_list('ActionName', Array(actions)))
  params.merge!('Label'    => label,
                :queue_url => queue_url )
  req_hash = generate_request('AddPermission', params)
  request_info(req_hash, SqsStatusParser.new(:logger => @logger))
rescue
  on_exception
end

#change_message_visibility(queue_url, receipt_handle, visibility_timeout) ⇒ Object

Change the visibility timeout of a specified message in a queue.

sqs.change_message_visibility('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'Euvo62...kw==', 33) #=> true

see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryChangeMessageVisibility.html


299
300
301
302
303
304
305
306
307
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 299

def change_message_visibility(queue_url, receipt_handle, visibility_timeout)
  req_hash = generate_request('ChangeMessageVisibility',
                              'ReceiptHandle'     => receipt_handle,
                              'VisibilityTimeout' => visibility_timeout,
                              :queue_url          => queue_url )
  request_info(req_hash, SqsStatusParser.new(:logger => @logger))
rescue
  on_exception
end

#clear_queue(queue_url) ⇒ Object

Removes all visible messages from queue. Return true or an exception.

sqs.clear_queue('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> true


401
402
403
404
405
406
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 401

def clear_queue(queue_url)
  while (pop_messages(queue_url, 10).length > 0) ; end   # delete all messages in queue
  true
rescue
  on_exception
end

#create_queue(queue_name, default_visibility_timeout = nil) ⇒ Object

Creates a new queue, returning its URI.

sqs.create_queue('my_awesome_queue') #=> 'https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'


149
150
151
152
153
154
155
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 149

def create_queue(queue_name, default_visibility_timeout=nil)
  req_hash = generate_request('CreateQueue', 'QueueName' => queue_name,
                              'DefaultVisibilityTimeout' => default_visibility_timeout || DEFAULT_VISIBILITY_TIMEOUT )
  request_info(req_hash, SqsCreateQueueParser.new(:logger => @logger))
rescue
  on_exception
end

#delete_message(queue_url, receipt_handle) ⇒ Object

Deletes message from queue. Returns true or an exception. Amazon returns true on deletion of non-existent messages. You must use the receipt handle for a message to delete it, not the message ID.

From the SQS Developer Guide: “It is possible you will receive a message even after you have deleted it. This might happen on rare occasions if one of the servers storing a copy of the message is unavailable when you request to delete the message. The copy remains on the server and might be returned to you again on a subsequent receive request. You should create your system to be idempotent so that receiving a particular message more than once is not a problem. ”

sqs.delete_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'Euvo62/1nlIet...ao03hd9Sa0w==') #=> true


344
345
346
347
348
349
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 344

def delete_message(queue_url, receipt_handle)
  req_hash = generate_request('DeleteMessage', 'ReceiptHandle' => receipt_handle, :queue_url  => queue_url)
  request_info(req_hash, SqsStatusParser.new(:logger => @logger))
rescue
  on_exception
end

#delete_queue(queue_url) ⇒ Object

Deletes queue. Any messages in the queue are permanently lost. Returns true or an exception. Queue deletion can take up to 60 s to propagate through SQS. Thus, after a deletion, subsequent list_queues calls may still show the deleted queue. It is not unusual within the 60 s window to see the deleted queue absent from one list_queues call but present in the subsequent one. Deletion is eventual.

sqs.delete_queue('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2') #=> true


180
181
182
183
184
185
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 180

def delete_queue(queue_url)
  req_hash = generate_request('DeleteQueue', :queue_url => queue_url)
  request_info(req_hash, SqsStatusParser.new(:logger => @logger))
rescue
  on_exception
end

#generate_post_request(action, param = {}) ⇒ Object

:nodoc:



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 116

def generate_post_request(action, param={})  # :nodoc:
  service = param[:queue_url] ? URI(param[:queue_url]).path : '/'
  message   = param[:message]                # extract message body if nesessary
  param.each{ |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
  service_hash = { "Action"           => action,
                   "Expires"          => (Time.now + REQUEST_TTL).utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
                   "AWSAccessKeyId"   => @aws_access_key_id,
                   "MessageBody"      => message,
                   "Version"          => API_VERSION }
  service_hash.update(param)
  #
  service_params = signed_service_params(@aws_secret_access_key, service_hash, :post, @params[:server], service)
  request        = Net::HTTP::Post.new(AwsUtils::URLencode(service))
  request['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
  request.body = service_params
    # prepare output hash
  { :request  => request, 
    :server   => @params[:server],
    :port     => @params[:port],
    :protocol => @params[:protocol] }
end

#generate_request(action, param = {}) ⇒ Object

Generates a request hash for the query API



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 93

def generate_request(action, param={})  # :nodoc:
  # For operation requests on a queue, the queue URI will be a parameter,
  # so we first extract it from the call parameters.  Next we remove any
  # parameters with no value or with symbolic keys.  We add the header
  # fields required in all requests, and then the headers passed in as
  # params.  We sort the header fields alphabetically and then generate the
  # signature before URL escaping the resulting query and sending it.
  service = param[:queue_url] ? URI(param[:queue_url]).path : '/'
  param.each{ |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
  service_hash = { "Action"           => action,
                   "Expires"          => (Time.now + REQUEST_TTL).utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
                   "AWSAccessKeyId"   => @aws_access_key_id,
                   "Version"          => API_VERSION }
  service_hash.update(param)
  service_params = signed_service_params(@aws_secret_access_key, service_hash, :get, @params[:server], service)
  request        = Net::HTTP::Get.new("#{AwsUtils.URLencode(service)}?#{service_params}")
    # prepare output hash
  { :request  => request, 
    :server   => @params[:server],
    :port     => @params[:port],
    :protocol => @params[:protocol] }
end

#get_queue_attributes(queue_url, *attributes) ⇒ Object

Retrieves the queue attribute(s). Returns a hash of attribute(s) or an exception.

sqs.get_queue_attributes('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=>
  {"ApproximateNumberOfMessages" => "0",
   "LastModifiedTimestamp"       => "1240946032",
   "CreatedTimestamp"            => "1240816887",
   "VisibilityTimeout"           => "30",
   "Policy"                      => "{"Version":"2008-10-17","Id":...}"}

queue.get_queue_attributes('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', "LastModifiedTimestamp", "VisibilityTimeout") #=>
  {"LastModifiedTimestamp" => "1240946032",
   "VisibilityTimeout"     => "30"}

docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryGetQueueAttributes.html



201
202
203
204
205
206
207
208
209
210
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 201

def get_queue_attributes(queue_url, *attributes)
  attributes.flatten!
  attributes << 'All' if attributes.right_blank?
  params = amazonize_list('AttributeName', attributes)
  params.merge!(:queue_url  => queue_url)
  req_hash = generate_request('GetQueueAttributes', params)
  request_info(req_hash, SqsGetQueueAttributesParser.new(:logger => @logger))
rescue
  on_exception
end

#get_queue_length(queue_url) ⇒ Object

Returns approximate number of messages in queue.

sqs.get_queue_length('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 3


389
390
391
392
393
394
395
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 389

def get_queue_length(queue_url)
  attrs = get_queue_attributes(queue_url)
  attrs['ApproximateNumberOfMessages'].to_i +
  attrs['ApproximateNumberOfMessagesNotVisible'].to_i
rescue
  on_exception
end

#list_queues(queue_name_prefix = nil) ⇒ Object

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. Queue creation is an eventual operation and created queues may not show up in immediately subsequent list_queues calls.

sqs.create_queue('my_awesome_queue')
sqs.create_queue('my_awesome_queue_2')
sqs.list_queues('my_awesome') #=> ['https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue','https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue_2']


165
166
167
168
169
170
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 165

def list_queues(queue_name_prefix=nil)
  req_hash = generate_request('ListQueues', 'QueueNamePrefix' => queue_name_prefix)
  request_info(req_hash, SqsListQueuesParser.new(:logger => @logger))
rescue
  on_exception
end

#pop_message(queue_url, attributes = nil) ⇒ Object

Pops (retrieves and deletes) first accessible message from queue. Returns the message in format {:id=>'message_id', :body=>'message_body'} or nil.

sqs.pop_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=>
  {:id=>"12345678904GEZX9746N|0N9ED344VK5Z3SV1DTM0|1RVYH4X3TJ0987654321", :body=>"message_1"}


429
430
431
432
433
434
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 429

def pop_message(queue_url, attributes=nil)
  messages = pop_messages(queue_url, 1, attributes)
  messages.right_blank? ? nil : messages[0]
rescue
  on_exception
end

#pop_messages(queue_url, number_of_messages = 1, attributes = nil) ⇒ Object

Pops (retrieves and deletes) up to ‘number_of_messages’ from queue. Returns an array of retrieved messages in format: [{:id=>'message_id', :body=>'message_body'}].

sqs.pop_messages('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 3) #=>
[{"ReceiptHandle"=>"Euvo62/...+Zw==", "MD5OfBody"=>"16af2...81e3", "Body"=>"Goodbyte World!", 
"MessageId"=>"MEZI...JSWDE="}, {...}, ... , {...} ]


414
415
416
417
418
419
420
421
422
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 414

def pop_messages(queue_url, number_of_messages=1, attributes=nil)
  messages = receive_message(queue_url, number_of_messages, nil, attributes)
  messages.each do |message|
    delete_message(queue_url, message['ReceiptHandle'])
  end
  messages
rescue
  on_exception
end

#queue_name_by_url(queue_url) ⇒ Object

Returns short queue name by url.

sqs.queue_name_by_url('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue') #=> 'my_awesome_queue'


379
380
381
382
383
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 379

def queue_name_by_url(queue_url)
  self.class.queue_name_by_url(queue_url)
rescue
  on_exception
end

#queue_url_by_name(queue_name) ⇒ Object

Given the queue’s short name, this call returns the queue URL or nil if queue is not found

sqs.queue_url_by_name('my_awesome_queue') #=> 'https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue'


354
355
356
357
358
359
360
361
362
363
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 354

def queue_url_by_name(queue_name)
  return queue_name if queue_name.include?('/')
  queue_urls = list_queues(queue_name)
  queue_urls.each do |queue_url|
    return queue_url if queue_name_by_url(queue_url) == queue_name
  end
  nil
rescue
  on_exception
end

#receive_message(queue_url, max_number_of_messages = 1, visibility_timeout = nil, attributes = nil) ⇒ Object

Retrieves a list of messages from queue. Returns an array of hashes in format: {:id=>'message_id', :body=>'message_body'}

sqs.receive_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',10, 5) #=>
 [{"ReceiptHandle"=>"Euvo62...kw==", "MD5OfBody"=>"16af2171b5b83cfa35ce254966ba81e3", 
   "Body"=>"Goodbyte World!", "MessageId"=>"MUM4WlAyR...pYOTA="}, ..., {}]

Normally this call returns fewer messages than the maximum specified, even if they are available.



281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 281

def receive_message(queue_url, max_number_of_messages=1, visibility_timeout=nil, attributes=nil)
  return [] if max_number_of_messages == 0
  params = {}
  params.merge!(amazonize_list('AttributeName', Array(attributes))) unless attributes.right_blank?
  params.merge!('MaxNumberOfMessages' => max_number_of_messages,
                'VisibilityTimeout'   => visibility_timeout,
                :queue_url            => queue_url )
  req_hash = generate_post_request('ReceiveMessage', params)
  request_info(req_hash, SqsReceiveMessageParser.new(:logger => @logger))
rescue
  on_exception
end

#remove_permissions(queue_url, label) ⇒ Object

Revoke any permissions in the queue policy that matches the label parameter.

sqs.remove_permissions('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue',
                      'testLabel') # => true

see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryRemovePermission.html


263
264
265
266
267
268
269
270
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 263

def remove_permissions(queue_url, label)
  req_hash = generate_request('RemovePermission',
                              'Label'    => label,
                              :queue_url => queue_url )
  request_info(req_hash, SqsStatusParser.new(:logger => @logger))
rescue
  on_exception
end

#request_info(request, parser) ⇒ Object

Sends request to Amazon and parses the response Raises AwsError if any banana happened



141
142
143
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 141

def request_info(request, parser) # :nodoc:
  request_info_impl(:sqs_connection, @@bench, request, parser)
end

#send_message(queue_url, message) ⇒ Object Also known as: push_message

Sends a new message to a queue. Message size is limited to 8 KB. If successful, this call returns a hash containing key/value pairs for “MessageId” and “MD5OfMessageBody”:

sqs.send_message('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', 'message_1') #=> 
  {"MessageId"=>"MEs4M0JKNlRCRTBBSENaMjROTk58QVFRNzNEREhDVFlFOVJDQ1JKNjF8UTdBRllCUlJUMjhKMUI1WDJSWDE=",
   "MD5OfMessageBody"=>"16af2171b5b83cfa35ce254966ba81e3"}

On failure, send_message raises an exception.



320
321
322
323
324
325
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 320

def send_message(queue_url, message)
  req_hash = generate_post_request('SendMessage', :message  => message, :queue_url => queue_url)
  request_info(req_hash, SqsSendMessagesParser.new(:logger => @logger))
rescue
  on_exception
end

#set_queue_attributes(queue_url, attribute, value) ⇒ Object

Sets queue attribute. Returns true or an exception.

sqs.set_queue_attributes('https://queue.amazonaws.com/ZZ7XXXYYYBINS/my_awesome_queue', "VisibilityTimeout", 10) #=> true

From the SQS Dev Guide: “When you change a queue’s attributes, the change can take up to 60 seconds to propagate throughout the SQS system.”

NB: Attribute values may not be immediately available to other queries for some time after an update. See the SQS documentation for semantics, but in general propagation can take up to 60 s.

see http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QuerySetQueueAttributes.html


225
226
227
228
229
230
231
232
233
# File 'lib/sqs/right_sqs_gen2_interface.rb', line 225

def set_queue_attributes(queue_url, attribute, value)
  req_hash = generate_request('SetQueueAttributes', 
                              'Attribute.Name'  => attribute,
                              'Attribute.Value' => value,
                              :queue_url        => queue_url)
  request_info(req_hash, SqsStatusParser.new(:logger => @logger))
rescue
  on_exception
end