PageRenderTime 51ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/boto-2.5.2/boto/sns/connection.py

#
Python | 441 lines | 375 code | 21 blank | 45 comment | 17 complexity | de4b285a100a64257223f62a52881a01 MD5 | raw file
  1. # Copyright (c) 2010 Mitch Garnaat http://garnaat.org/
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a
  4. # copy of this software and associated documentation files (the
  5. # "Software"), to deal in the Software without restriction, including
  6. # without limitation the rights to use, copy, modify, merge, publish, dis-
  7. # tribute, sublicense, and/or sell copies of the Software, and to permit
  8. # persons to whom the Software is furnished to do so, subject to the fol-
  9. # lowing conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included
  12. # in all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
  16. # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  17. # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  18. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. # IN THE SOFTWARE.
  21. from boto.connection import AWSQueryConnection
  22. from boto.regioninfo import RegionInfo
  23. import boto
  24. import uuid
  25. try:
  26. import simplejson as json
  27. except ImportError:
  28. import json
  29. class SNSConnection(AWSQueryConnection):
  30. DefaultRegionName = 'us-east-1'
  31. DefaultRegionEndpoint = 'sns.us-east-1.amazonaws.com'
  32. APIVersion = '2010-03-31'
  33. def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
  34. is_secure=True, port=None, proxy=None, proxy_port=None,
  35. proxy_user=None, proxy_pass=None, debug=0,
  36. https_connection_factory=None, region=None, path='/',
  37. security_token=None):
  38. if not region:
  39. region = RegionInfo(self, self.DefaultRegionName,
  40. self.DefaultRegionEndpoint,
  41. connection_cls=SNSConnection)
  42. self.region = region
  43. AWSQueryConnection.__init__(self, aws_access_key_id,
  44. aws_secret_access_key,
  45. is_secure, port, proxy, proxy_port,
  46. proxy_user, proxy_pass,
  47. self.region.endpoint, debug,
  48. https_connection_factory, path,
  49. security_token=security_token)
  50. def _required_auth_capability(self):
  51. return ['sns']
  52. def _credentials_expired(self, response):
  53. if response.status != 403:
  54. return False
  55. try:
  56. parsed = json.loads(response.read())
  57. return parsed['Error']['Code'] == 'ExpiredToken'
  58. except Exception:
  59. return False
  60. return False
  61. def get_all_topics(self, next_token=None):
  62. """
  63. :type next_token: string
  64. :param next_token: Token returned by the previous call to
  65. this method.
  66. """
  67. params = {'ContentType' : 'JSON'}
  68. if next_token:
  69. params['NextToken'] = next_token
  70. response = self.make_request('ListTopics', params, '/', 'GET')
  71. body = response.read()
  72. if response.status == 200:
  73. return json.loads(body)
  74. else:
  75. boto.log.error('%s %s' % (response.status, response.reason))
  76. boto.log.error('%s' % body)
  77. raise self.ResponseError(response.status, response.reason, body)
  78. def get_topic_attributes(self, topic):
  79. """
  80. Get attributes of a Topic
  81. :type topic: string
  82. :param topic: The ARN of the topic.
  83. """
  84. params = {'ContentType' : 'JSON',
  85. 'TopicArn' : topic}
  86. response = self.make_request('GetTopicAttributes', params, '/', 'GET')
  87. body = response.read()
  88. if response.status == 200:
  89. return json.loads(body)
  90. else:
  91. boto.log.error('%s %s' % (response.status, response.reason))
  92. boto.log.error('%s' % body)
  93. raise self.ResponseError(response.status, response.reason, body)
  94. def set_topic_attributes(self, topic, attr_name, attr_value):
  95. """
  96. Get attributes of a Topic
  97. :type topic: string
  98. :param topic: The ARN of the topic.
  99. :type attr_name: string
  100. :param attr_name: The name of the attribute you want to set.
  101. Only a subset of the topic's attributes are mutable.
  102. Valid values: Policy | DisplayName
  103. :type attr_value: string
  104. :param attr_value: The new value for the attribute.
  105. """
  106. params = {'ContentType' : 'JSON',
  107. 'TopicArn' : topic,
  108. 'AttributeName' : attr_name,
  109. 'AttributeValue' : attr_value}
  110. response = self.make_request('SetTopicAttributes', params, '/', 'GET')
  111. body = response.read()
  112. if response.status == 200:
  113. return json.loads(body)
  114. else:
  115. boto.log.error('%s %s' % (response.status, response.reason))
  116. boto.log.error('%s' % body)
  117. raise self.ResponseError(response.status, response.reason, body)
  118. def add_permission(self, topic, label, account_ids, actions):
  119. """
  120. Adds a statement to a topic's access control policy, granting
  121. access for the specified AWS accounts to the specified actions.
  122. :type topic: string
  123. :param topic: The ARN of the topic.
  124. :type label: string
  125. :param label: A unique identifier for the new policy statement.
  126. :type account_ids: list of strings
  127. :param account_ids: The AWS account ids of the users who will be
  128. give access to the specified actions.
  129. :type actions: list of strings
  130. :param actions: The actions you want to allow for each of the
  131. specified principal(s).
  132. """
  133. params = {'ContentType' : 'JSON',
  134. 'TopicArn' : topic,
  135. 'Label' : label}
  136. self.build_list_params(params, account_ids, 'AWSAccountId')
  137. self.build_list_params(params, actions, 'ActionName')
  138. response = self.make_request('AddPermission', params, '/', 'GET')
  139. body = response.read()
  140. if response.status == 200:
  141. return json.loads(body)
  142. else:
  143. boto.log.error('%s %s' % (response.status, response.reason))
  144. boto.log.error('%s' % body)
  145. raise self.ResponseError(response.status, response.reason, body)
  146. def remove_permission(self, topic, label):
  147. """
  148. Removes a statement from a topic's access control policy.
  149. :type topic: string
  150. :param topic: The ARN of the topic.
  151. :type label: string
  152. :param label: A unique identifier for the policy statement
  153. to be removed.
  154. """
  155. params = {'ContentType' : 'JSON',
  156. 'TopicArn' : topic,
  157. 'Label' : label}
  158. response = self.make_request('RemovePermission', params, '/', 'GET')
  159. body = response.read()
  160. if response.status == 200:
  161. return json.loads(body)
  162. else:
  163. boto.log.error('%s %s' % (response.status, response.reason))
  164. boto.log.error('%s' % body)
  165. raise self.ResponseError(response.status, response.reason, body)
  166. def create_topic(self, topic):
  167. """
  168. Create a new Topic.
  169. :type topic: string
  170. :param topic: The name of the new topic.
  171. """
  172. params = {'ContentType' : 'JSON',
  173. 'Name' : topic}
  174. response = self.make_request('CreateTopic', params, '/', 'GET')
  175. body = response.read()
  176. if response.status == 200:
  177. return json.loads(body)
  178. else:
  179. boto.log.error('%s %s' % (response.status, response.reason))
  180. boto.log.error('%s' % body)
  181. raise self.ResponseError(response.status, response.reason, body)
  182. def delete_topic(self, topic):
  183. """
  184. Delete an existing topic
  185. :type topic: string
  186. :param topic: The ARN of the topic
  187. """
  188. params = {'ContentType' : 'JSON',
  189. 'TopicArn' : topic}
  190. response = self.make_request('DeleteTopic', params, '/', 'GET')
  191. body = response.read()
  192. if response.status == 200:
  193. return json.loads(body)
  194. else:
  195. boto.log.error('%s %s' % (response.status, response.reason))
  196. boto.log.error('%s' % body)
  197. raise self.ResponseError(response.status, response.reason, body)
  198. def publish(self, topic, message, subject=None):
  199. """
  200. Get properties of a Topic
  201. :type topic: string
  202. :param topic: The ARN of the new topic.
  203. :type message: string
  204. :param message: The message you want to send to the topic.
  205. Messages must be UTF-8 encoded strings and
  206. be at most 4KB in size.
  207. :type subject: string
  208. :param subject: Optional parameter to be used as the "Subject"
  209. line of the email notifications.
  210. """
  211. params = {'ContentType' : 'JSON',
  212. 'TopicArn' : topic,
  213. 'Message' : message}
  214. if subject:
  215. params['Subject'] = subject
  216. response = self.make_request('Publish', params, '/', 'GET')
  217. body = response.read()
  218. if response.status == 200:
  219. return json.loads(body)
  220. else:
  221. boto.log.error('%s %s' % (response.status, response.reason))
  222. boto.log.error('%s' % body)
  223. raise self.ResponseError(response.status, response.reason, body)
  224. def subscribe(self, topic, protocol, endpoint):
  225. """
  226. Subscribe to a Topic.
  227. :type topic: string
  228. :param topic: The name of the new topic.
  229. :type protocol: string
  230. :param protocol: The protocol used to communicate with
  231. the subscriber. Current choices are:
  232. email|email-json|http|https|sqs
  233. :type endpoint: string
  234. :param endpoint: The location of the endpoint for
  235. the subscriber.
  236. * For email, this would be a valid email address
  237. * For email-json, this would be a valid email address
  238. * For http, this would be a URL beginning with http
  239. * For https, this would be a URL beginning with https
  240. * For sqs, this would be the ARN of an SQS Queue
  241. """
  242. params = {'ContentType' : 'JSON',
  243. 'TopicArn' : topic,
  244. 'Protocol' : protocol,
  245. 'Endpoint' : endpoint}
  246. response = self.make_request('Subscribe', params, '/', 'GET')
  247. body = response.read()
  248. if response.status == 200:
  249. return json.loads(body)
  250. else:
  251. boto.log.error('%s %s' % (response.status, response.reason))
  252. boto.log.error('%s' % body)
  253. raise self.ResponseError(response.status, response.reason, body)
  254. def subscribe_sqs_queue(self, topic, queue):
  255. """
  256. Subscribe an SQS queue to a topic.
  257. This is convenience method that handles most of the complexity involved
  258. in using an SQS queue as an endpoint for an SNS topic. To achieve this
  259. the following operations are performed:
  260. * The correct ARN is constructed for the SQS queue and that ARN is
  261. then subscribed to the topic.
  262. * A JSON policy document is contructed that grants permission to
  263. the SNS topic to send messages to the SQS queue.
  264. * This JSON policy is then associated with the SQS queue using
  265. the queue's set_attribute method. If the queue already has
  266. a policy associated with it, this process will add a Statement to
  267. that policy. If no policy exists, a new policy will be created.
  268. :type topic: string
  269. :param topic: The name of the new topic.
  270. :type queue: A boto Queue object
  271. :param queue: The queue you wish to subscribe to the SNS Topic.
  272. """
  273. t = queue.id.split('/')
  274. q_arn = 'arn:aws:sqs:%s:%s:%s' % (queue.connection.region.name,
  275. t[1], t[2])
  276. resp = self.subscribe(topic, 'sqs', q_arn)
  277. policy = queue.get_attributes('Policy')
  278. if 'Version' not in policy:
  279. policy['Version'] = '2008-10-17'
  280. if 'Statement' not in policy:
  281. policy['Statement'] = []
  282. statement = {'Action' : 'SQS:SendMessage',
  283. 'Effect' : 'Allow',
  284. 'Principal' : {'AWS' : '*'},
  285. 'Resource' : q_arn,
  286. 'Sid' : str(uuid.uuid4()),
  287. 'Condition' : {'StringLike' : {'aws:SourceArn' : topic}}}
  288. policy['Statement'].append(statement)
  289. queue.set_attribute('Policy', json.dumps(policy))
  290. return resp
  291. def confirm_subscription(self, topic, token,
  292. authenticate_on_unsubscribe=False):
  293. """
  294. Get properties of a Topic
  295. :type topic: string
  296. :param topic: The ARN of the new topic.
  297. :type token: string
  298. :param token: Short-lived token sent to and endpoint during
  299. the Subscribe operation.
  300. :type authenticate_on_unsubscribe: bool
  301. :param authenticate_on_unsubscribe: Optional parameter indicating
  302. that you wish to disable
  303. unauthenticated unsubscription
  304. of the subscription.
  305. """
  306. params = {'ContentType' : 'JSON',
  307. 'TopicArn' : topic,
  308. 'Token' : token}
  309. if authenticate_on_unsubscribe:
  310. params['AuthenticateOnUnsubscribe'] = 'true'
  311. response = self.make_request('ConfirmSubscription', params, '/', 'GET')
  312. body = response.read()
  313. if response.status == 200:
  314. return json.loads(body)
  315. else:
  316. boto.log.error('%s %s' % (response.status, response.reason))
  317. boto.log.error('%s' % body)
  318. raise self.ResponseError(response.status, response.reason, body)
  319. def unsubscribe(self, subscription):
  320. """
  321. Allows endpoint owner to delete subscription.
  322. Confirmation message will be delivered.
  323. :type subscription: string
  324. :param subscription: The ARN of the subscription to be deleted.
  325. """
  326. params = {'ContentType' : 'JSON',
  327. 'SubscriptionArn' : subscription}
  328. response = self.make_request('Unsubscribe', params, '/', 'GET')
  329. body = response.read()
  330. if response.status == 200:
  331. return json.loads(body)
  332. else:
  333. boto.log.error('%s %s' % (response.status, response.reason))
  334. boto.log.error('%s' % body)
  335. raise self.ResponseError(response.status, response.reason, body)
  336. def get_all_subscriptions(self, next_token=None):
  337. """
  338. Get list of all subscriptions.
  339. :type next_token: string
  340. :param next_token: Token returned by the previous call to
  341. this method.
  342. """
  343. params = {'ContentType' : 'JSON'}
  344. if next_token:
  345. params['NextToken'] = next_token
  346. response = self.make_request('ListSubscriptions', params, '/', 'GET')
  347. body = response.read()
  348. if response.status == 200:
  349. return json.loads(body)
  350. else:
  351. boto.log.error('%s %s' % (response.status, response.reason))
  352. boto.log.error('%s' % body)
  353. raise self.ResponseError(response.status, response.reason, body)
  354. def get_all_subscriptions_by_topic(self, topic, next_token=None):
  355. """
  356. Get list of all subscriptions to a specific topic.
  357. :type topic: string
  358. :param topic: The ARN of the topic for which you wish to
  359. find subscriptions.
  360. :type next_token: string
  361. :param next_token: Token returned by the previous call to
  362. this method.
  363. """
  364. params = {'ContentType' : 'JSON',
  365. 'TopicArn' : topic}
  366. if next_token:
  367. params['NextToken'] = next_token
  368. response = self.make_request('ListSubscriptionsByTopic', params,
  369. '/', 'GET')
  370. body = response.read()
  371. if response.status == 200:
  372. return json.loads(body)
  373. else:
  374. boto.log.error('%s %s' % (response.status, response.reason))
  375. boto.log.error('%s' % body)
  376. raise self.ResponseError(response.status, response.reason, body)