Class: RightAws::SnsInterface

Inherits:
RightAwsBase show all
Includes:
RightAwsBaseInterface
Defined in:
lib/sns/right_sns_interface.rb

Defined Under Namespace

Classes: SnsConfirmSubscriptionParser, SnsCreateTopicParser, SnsGetTopicAttributesParser, SnsListSubscriptionsParser, SnsListTopicsParser, SnsPublishParser, SnsSubscribeParser

Constant Summary collapse

DEFAULT_HOST =
'sns.us-east-1.amazonaws.com'
DEFAULT_PORT =
443
DEFAULT_PROTOCOL =
'https'
DEFAULT_SERVICE =
'/'
REQUEST_TTL =
30
@@bench =

Apparently boilerplate stuff

AwsBenchmarkingBlock.new

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_hash_with_key_mapping, #amazonize_list, #amazonize_list_with_key_mapping, #cache_hits?, caching, caching=, #caching?, #destroy_connection, #generate_request_impl, #get_connection, #get_connections_storage, #get_server_url, #incrementally_list_items, #init, #map_api_keys_and_values, #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 = {}) ⇒ SnsInterface

Returns a new instance of SnsInterface.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/sns/right_sns_interface.rb', line 43

def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
  if params[:region]
    server = "sns.#{params[:region]}.amazonaws.com"
    params.delete(:region)
  else
    server = DEFAULT_HOST
  end
  init({  :name               => 'SNS',
          :default_host       => ENV['SNS_URL'] ? URI.parse(ENV['SNS_URL']).host    : server,
          :default_port       => ENV['SNS_URL'] ? URI.parse(ENV['SNS_URL']).port    : DEFAULT_PORT,
          :default_service    => ENV['SNS_URL'] ? URI.parse(ENV['SNS_URL']).path    : DEFAULT_SERVICE,
          :default_protocol   => ENV['SNS_URL'] ? URI.parse(ENV['SNS_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

.bench_serviceObject



39
40
41
# File 'lib/sns/right_sns_interface.rb', line 39

def self.bench_service
  @@bench.service
end

.bench_xmlObject



36
37
38
# File 'lib/sns/right_sns_interface.rb', line 36

def self.bench_xml
  @@bench.xml
end

Instance Method Details

#add_permission(topic_arn, label, acct_action_hash_ary) ⇒ Object



171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/sns/right_sns_interface.rb', line 171

def add_permission(topic_arn, label, acct_action_hash_ary)
  n_hash = {
    'TopicArn'  => topic_arn,
    'Label'     => label
  }

  acct_action_hash_ary.each_with_index do |hash_val, idx|
    n_hash["AWSAccountId.member.#{idx+1}"]  = hash_val[:aws_account_id]
    n_hash["ActionName.member.#{idx+1}"]    = hash_val[:action]
  end

  req_hash = generate_request('AddPermission', n_hash)
  request_info(req_hash, RightHttp2xxParser.new)
end

#confirm_subscription(topic_arn, token, authenticate_on_unsubscribe = false) ⇒ Object



166
167
168
169
# File 'lib/sns/right_sns_interface.rb', line 166

def confirm_subscription(topic_arn, token, authenticate_on_unsubscribe=false)
  req_hash = generate_request('ConfirmSubscription', 'AuthenticateOnUnsubscribe' => authenticate_on_unsubscribe.to_s, 'Token' => token, 'TopicArn' => topic_arn)
  request_info(req_hash, SnsConfirmSubscriptionParser.new)
end

#create_topic(topic_name) ⇒ Object



117
118
119
120
# File 'lib/sns/right_sns_interface.rb', line 117

def create_topic(topic_name)
  req_hash = generate_request('CreateTopic', 'Name' => topic_name)
  request_info(req_hash, SnsCreateTopicParser.new)
end

#delete_topic(topic_arn) ⇒ Object



127
128
129
130
# File 'lib/sns/right_sns_interface.rb', line 127

def delete_topic(topic_arn)
  req_hash = generate_request('DeleteTopic', 'TopicArn' => topic_arn)
  request_info(req_hash, RightHttp2xxParser.new)
end

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

TODO: RJG - Seems like generate_request and generate_rest_request could be in a sub class? Generates a request hash for the sns API



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/sns/right_sns_interface.rb', line 62

def generate_request(action, params={})  # :nodoc:
    # Sometimes we need to use queue uri (delete queue etc)
    # In that case we will use Symbol key: 'param[:queue_url]'
  service = params[:sns_url] ? URI(params[:sns_url]).path : '/'
    # remove unset(=optional) and symbolyc keys
  params.each{ |key, value| params.delete(key) if (value.nil? || key.is_a?(Symbol)) }
    # prepare output hash
  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(params)
  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

#generate_rest_request(method, param) ⇒ Object

Generates a request hash for the REST API



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/sns/right_sns_interface.rb', line 84

def generate_rest_request(method, param) # :nodoc:
  sns_uri = param[:sns_url] ? URI(param[:sns_url]).path : '/'
  message   = param[:message]                # extract message body if nesessary
    # remove unset(=optional) and symbolyc keys
  param.each{ |key, value| param.delete(key) if (value.nil? || key.is_a?(Symbol)) }
    # created request
  param_to_str = param.to_a.collect{|key,val| key.to_s + "=" + CGI::escape(val.to_s) }.join("&")
  param_to_str = "?#{param_to_str}" unless param_to_str.right_blank?
  request = "Net::HTTP::#{method.capitalize}".right_constantize.new("#{sns_uri}#{param_to_str}")
  request.body = message if message
    # set main headers
  request['content-md5']  = ''
  request['Content-Type'] = 'text/plain'
  request['Date']         = Time.now.httpdate
    # generate authorization string
  auth_string = "#{method.upcase}\n#{request['content-md5']}\n#{request['Content-Type']}\n#{request['Date']}\n#{CGI::unescape(sns_uri)}"
  signature   = AwsUtils::sign(@aws_secret_access_key, auth_string)
    # set other headers
  request['Authorization'] = "AWS #{@aws_access_key_id}:#{signature}"
  #request['AWS-Version']   = API_VERSION
    # prepare output hash
  { :request  => request,
    :server   => @params[:server],
    :port     => @params[:port],
    :protocol => @params[:protocol] }
end

#get_topic_attributes(topic_arn) ⇒ Object



155
156
157
158
# File 'lib/sns/right_sns_interface.rb', line 155

def get_topic_attributes(topic_arn)
  req_hash = generate_request('GetTopicAttributes', 'TopicArn' => topic_arn)
  request_info(req_hash, SnsGetTopicAttributesParser.new)
end

#list_subscriptions(topic_arn = nil) ⇒ Object

Calls either the ListSubscriptions or ListSubscriptionsByTopic depending on whether or not the topic_arn parameter is provided.



161
162
163
164
# File 'lib/sns/right_sns_interface.rb', line 161

def list_subscriptions(topic_arn = nil)
  req_hash = topic_arn ? generate_request('ListSubscriptionsByTopic', 'TopicArn' => topic_arn) : generate_request('ListSubscriptions')
  request_info(req_hash, SnsListSubscriptionsParser.new)
end

#list_topicsObject



122
123
124
125
# File 'lib/sns/right_sns_interface.rb', line 122

def list_topics()
  req_hash = generate_request('ListTopics')
  request_info(req_hash, SnsListTopicsParser.new)
end

#publish(topic_arn, message, subject) ⇒ Object



142
143
144
145
# File 'lib/sns/right_sns_interface.rb', line 142

def publish(topic_arn, message, subject)
  req_hash = generate_request('Publish', 'TopicArn' => topic_arn, 'Message' => message, 'Subject' => subject)
  request_info(req_hash, SnsPublishParser.new)
end

#remove_permission(topic_arn, label) ⇒ Object



186
187
188
189
# File 'lib/sns/right_sns_interface.rb', line 186

def remove_permission(topic_arn, label)
  req_hash = generate_request('RemovePermission', 'TopicArn' => topic_arn, 'Label' => label)
  request_info(req_hash, RightHttp2xxParser.new)
end

#request_info(request, parser) ⇒ Object

Raises AwsError if any banana happened



113
114
115
# File 'lib/sns/right_sns_interface.rb', line 113

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

#set_topic_attribute(topic_arn, attribute_name, attribute_value) ⇒ Object



147
148
149
150
151
152
153
# File 'lib/sns/right_sns_interface.rb', line 147

def set_topic_attribute(topic_arn, attribute_name, attribute_value)
  if attribute_name != 'Policy' && attribute_name != 'DisplayName'
    raise(ArgumentError, "The only values accepted for the attribute_name parameter are (Policy, DisplayName)")
  end
  req_hash = generate_request('SetTopicAttributes', 'TopicArn' => topic_arn, 'AttributeName' => attribute_name, 'AttributeValue' => attribute_value)
  request_info(req_hash, RightHttp2xxParser.new)
end

#subscribe(topic_arn, protocol, endpoint) ⇒ Object



132
133
134
135
# File 'lib/sns/right_sns_interface.rb', line 132

def subscribe(topic_arn, protocol, endpoint)
  req_hash = generate_request('Subscribe', 'TopicArn' => topic_arn, 'Protocol' => protocol, 'Endpoint' => endpoint)
  request_info(req_hash, SnsSubscribeParser.new)
end

#unsubscribe(subscription_arn) ⇒ Object



137
138
139
140
# File 'lib/sns/right_sns_interface.rb', line 137

def unsubscribe(subscription_arn)
  req_hash = generate_request('Unsubscribe', 'SubscriptionArn' => subscription_arn)
  request_info(req_hash, RightHttp2xxParser.new)
end