Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SQS.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. """
  2. kombu.transport.SQS
  3. ===================
  4. Amazon SQS transport module for Kombu. This package implements an AMQP-like
  5. interface on top of Amazons SQS service, with the goal of being optimized for
  6. high performance and reliability.
  7. The default settings for this module are focused now on high performance in
  8. task queue situations where tasks are small, idempotent and run very fast.
  9. SQS Features supported by this transport:
  10. Long Polling:
  11. http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/
  12. sqs-long-polling.html
  13. Long polling is enabled by setting the `wait_time_seconds` transport
  14. option to a number > 1. Amazon supports up to 20 seconds. This is
  15. disabled for now, but will be enabled by default in the near future.
  16. Batch API Actions:
  17. http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/
  18. sqs-batch-api.html
  19. The default behavior of the SQS Channel.drain_events() method is to
  20. request up to the 'prefetch_count' messages on every request to SQS.
  21. These messages are stored locally in a deque object and passed back
  22. to the Transport until the deque is empty, before triggering a new
  23. API call to Amazon.
  24. This behavior dramatically speeds up the rate that you can pull tasks
  25. from SQS when you have short-running tasks (or a large number of workers).
  26. When a Celery worker has multiple queues to monitor, it will pull down
  27. up to 'prefetch_count' messages from queueA and work on them all before
  28. moving on to queueB. If queueB is empty, it will wait up until
  29. 'polling_interval' expires before moving back and checking on queueA.
  30. """
  31. from __future__ import absolute_import
  32. import collections
  33. import socket
  34. import string
  35. from anyjson import loads, dumps
  36. import boto
  37. from boto import exception
  38. from boto import sdb as _sdb
  39. from boto import sqs as _sqs
  40. from boto.sdb.domain import Domain
  41. from boto.sdb.connection import SDBConnection
  42. from boto.sqs.connection import SQSConnection
  43. from boto.sqs.message import Message
  44. from kombu.five import Empty, range, text_t
  45. from kombu.log import get_logger
  46. from kombu.utils import cached_property, uuid
  47. from kombu.utils.encoding import bytes_to_str, safe_str
  48. from kombu.transport.virtual import scheduling
  49. from . import virtual
  50. logger = get_logger(__name__)
  51. # dots are replaced by dash, all other punctuation
  52. # replaced by underscore.
  53. CHARS_REPLACE_TABLE = dict((ord(c), 0x5f)
  54. for c in string.punctuation if c not in '-_.')
  55. CHARS_REPLACE_TABLE[0x2e] = 0x2d # '.' -> '-'
  56. def maybe_int(x):
  57. try:
  58. return int(x)
  59. except ValueError:
  60. return x
  61. BOTO_VERSION = tuple(maybe_int(part) for part in boto.__version__.split('.'))
  62. W_LONG_POLLING = BOTO_VERSION >= (2, 8)
  63. #: SQS bulk get supports a maximum of 10 messages at a time.
  64. SQS_MAX_MESSAGES = 10
  65. class Table(Domain):
  66. """Amazon SimpleDB domain describing the message routing table."""
  67. # caches queues already bound, so we don't have to declare them again.
  68. _already_bound = set()
  69. def routes_for(self, exchange):
  70. """Iterator giving all routes for an exchange."""
  71. return self.select("""WHERE exchange = '%s'""" % exchange)
  72. def get_queue(self, queue):
  73. """Get binding for queue."""
  74. qid = self._get_queue_id(queue)
  75. if qid:
  76. return self.get_item(qid)
  77. def create_binding(self, queue):
  78. """Get binding item for queue.
  79. Creates the item if it doesn't exist.
  80. """
  81. item = self.get_queue(queue)
  82. if item:
  83. return item, item['id']
  84. id = uuid()
  85. return self.new_item(id), id
  86. def queue_bind(self, exchange, routing_key, pattern, queue):
  87. if queue not in self._already_bound:
  88. binding, id = self.create_binding(queue)
  89. binding.update(exchange=exchange,
  90. routing_key=routing_key or '',
  91. pattern=pattern or '',
  92. queue=queue or '',
  93. id=id)
  94. binding.save()
  95. self._already_bound.add(queue)
  96. def queue_delete(self, queue):
  97. """delete queue by name."""
  98. self._already_bound.discard(queue)
  99. item = self._get_queue_item(queue)
  100. if item:
  101. self.delete_item(item)
  102. def exchange_delete(self, exchange):
  103. """Delete all routes for `exchange`."""
  104. for item in self.routes_for(exchange):
  105. self.delete_item(item['id'])
  106. def get_item(self, item_name):
  107. """Uses `consistent_read` by default."""
  108. # Domain is an old-style class, can't use super().
  109. for consistent_read in (False, True):
  110. item = Domain.get_item(self, item_name, consistent_read)
  111. if item:
  112. return item
  113. def select(self, query='', next_token=None,
  114. consistent_read=True, max_items=None):
  115. """Uses `consistent_read` by default."""
  116. query = """SELECT * FROM `%s` %s""" % (self.name, query)
  117. return Domain.select(self, query, next_token,
  118. consistent_read, max_items)
  119. def _try_first(self, query='', **kwargs):
  120. for c in (False, True):
  121. for item in self.select(query, consistent_read=c, **kwargs):
  122. return item
  123. def get_exchanges(self):
  124. return list(set(i['exchange'] for i in self.select()))
  125. def _get_queue_item(self, queue):
  126. return self._try_first("""WHERE queue = '%s' limit 1""" % queue)
  127. def _get_queue_id(self, queue):
  128. item = self._get_queue_item(queue)
  129. if item:
  130. return item['id']
  131. class Channel(virtual.Channel):
  132. Table = Table
  133. default_region = 'us-east-1'
  134. default_visibility_timeout = 1800 # 30 minutes.
  135. default_wait_time_seconds = 0 # disabled see #198
  136. domain_format = 'kombu%(vhost)s'
  137. _sdb = None
  138. _sqs = None
  139. _queue_cache = {}
  140. _noack_queues = set()
  141. def __init__(self, *args, **kwargs):
  142. super(Channel, self).__init__(*args, **kwargs)
  143. # SQS blows up when you try to create a new queue if one already
  144. # exists with a different visibility_timeout, so this prepopulates
  145. # the queue_cache to protect us from recreating
  146. # queues that are known to already exist.
  147. queues = self.sqs.get_all_queues(prefix=self.queue_name_prefix)
  148. for queue in queues:
  149. self._queue_cache[queue.name] = queue
  150. self._fanout_queues = set()
  151. # The drain_events() method stores extra messages in a local
  152. # Deque object. This allows multiple messages to be requested from
  153. # SQS at once for performance, but maintains the same external API
  154. # to the caller of the drain_events() method.
  155. self._queue_message_cache = collections.deque()
  156. def basic_consume(self, queue, no_ack, *args, **kwargs):
  157. if no_ack:
  158. self._noack_queues.add(queue)
  159. return super(Channel, self).basic_consume(
  160. queue, no_ack, *args, **kwargs
  161. )
  162. def basic_cancel(self, consumer_tag):
  163. if consumer_tag in self._consumers:
  164. queue = self._tag_to_queue[consumer_tag]
  165. self._noack_queues.discard(queue)
  166. return super(Channel, self).basic_cancel(consumer_tag)
  167. def drain_events(self, timeout=None):
  168. """Return a single payload message from one of our queues.
  169. :raises Empty: if no messages available.
  170. """
  171. # If we're not allowed to consume or have no consumers, raise Empty
  172. if not self._consumers or not self.qos.can_consume():
  173. raise Empty()
  174. message_cache = self._queue_message_cache
  175. # Check if there are any items in our buffer. If there are any, pop
  176. # off that queue first.
  177. try:
  178. return message_cache.popleft()
  179. except IndexError:
  180. pass
  181. # At this point, go and get more messages from SQS
  182. res, queue = self._poll(self.cycle, timeout=timeout)
  183. message_cache.extend((r, queue) for r in res)
  184. # Now try to pop off the queue again.
  185. try:
  186. return message_cache.popleft()
  187. except IndexError:
  188. raise Empty()
  189. def _reset_cycle(self):
  190. """Reset the consume cycle.
  191. :returns: a FairCycle object that points to our _get_bulk() method
  192. rather than the standard _get() method. This allows for multiple
  193. messages to be returned at once from SQS (based on the prefetch
  194. limit).
  195. """
  196. self._cycle = scheduling.FairCycle(
  197. self._get_bulk, self._active_queues, Empty,
  198. )
  199. def entity_name(self, name, table=CHARS_REPLACE_TABLE):
  200. """Format AMQP queue name into a legal SQS queue name."""
  201. return text_t(safe_str(name)).translate(table)
  202. def _new_queue(self, queue, **kwargs):
  203. """Ensure a queue with given name exists in SQS."""
  204. # Translate to SQS name for consistency with initial
  205. # _queue_cache population.
  206. queue = self.entity_name(self.queue_name_prefix + queue)
  207. try:
  208. return self._queue_cache[queue]
  209. except KeyError:
  210. q = self._queue_cache[queue] = self.sqs.create_queue(
  211. queue, self.visibility_timeout,
  212. )
  213. return q
  214. def queue_bind(self, queue, exchange=None, routing_key='',
  215. arguments=None, **kwargs):
  216. super(Channel, self).queue_bind(queue, exchange, routing_key,
  217. arguments, **kwargs)
  218. if self.typeof(exchange).type == 'fanout':
  219. self._fanout_queues.add(queue)
  220. def _queue_bind(self, *args):
  221. """Bind ``queue`` to ``exchange`` with routing key.
  222. Route will be stored in SDB if so enabled.
  223. """
  224. if self.supports_fanout:
  225. self.table.queue_bind(*args)
  226. def get_table(self, exchange):
  227. """Get routing table.
  228. Retrieved from SDB if :attr:`supports_fanout`.
  229. """
  230. if self.supports_fanout:
  231. return [(r['routing_key'], r['pattern'], r['queue'])
  232. for r in self.table.routes_for(exchange)]
  233. return super(Channel, self).get_table(exchange)
  234. def get_exchanges(self):
  235. if self.supports_fanout:
  236. return self.table.get_exchanges()
  237. return super(Channel, self).get_exchanges()
  238. def _delete(self, queue, *args):
  239. """delete queue by name."""
  240. if self.supports_fanout:
  241. self.table.queue_delete(queue)
  242. super(Channel, self)._delete(queue)
  243. self._queue_cache.pop(queue, None)
  244. def exchange_delete(self, exchange, **kwargs):
  245. """Delete exchange by name."""
  246. if self.supports_fanout:
  247. self.table.exchange_delete(exchange)
  248. super(Channel, self).exchange_delete(exchange, **kwargs)
  249. def _has_queue(self, queue, **kwargs):
  250. """Return True if ``queue`` was previously declared."""
  251. if self.supports_fanout:
  252. return bool(self.table.get_queue(queue))
  253. return super(Channel, self)._has_queue(queue)
  254. def _put(self, queue, message, **kwargs):
  255. """Put message onto queue."""
  256. q = self._new_queue(queue)
  257. m = Message()
  258. m.set_body(dumps(message))
  259. q.write(m)
  260. def _put_fanout(self, exchange, message, routing_key, **kwargs):
  261. """Deliver fanout message to all queues in ``exchange``."""
  262. for route in self.table.routes_for(exchange):
  263. self._put(route['queue'], message, **kwargs)
  264. def _get_from_sqs(self, queue, count=1):
  265. """Retrieve messages from SQS and returns the raw SQS message objects.
  266. :returns: List of SQS message objects
  267. """
  268. q = self._new_queue(queue)
  269. if W_LONG_POLLING and queue not in self._fanout_queues:
  270. return q.get_messages(
  271. count, wait_time_seconds=self.wait_time_seconds,
  272. )
  273. else: # boto < 2.8
  274. return q.get_messages(count)
  275. def _message_to_python(self, message, queue_name, queue):
  276. payload = loads(bytes_to_str(message.get_body()))
  277. if queue_name in self._noack_queues:
  278. queue.delete_message(message)
  279. else:
  280. payload['properties']['delivery_info'].update({
  281. 'sqs_message': message, 'sqs_queue': queue,
  282. })
  283. return payload
  284. def _messages_to_python(self, messages, queue):
  285. """Convert a list of SQS Message objects into Payloads.
  286. This method handles converting SQS Message objects into
  287. Payloads, and appropriately updating the queue depending on
  288. the 'ack' settings for that queue.
  289. :param messages: A list of SQS Message objects.
  290. :param queue: String name representing the queue they came from
  291. :returns: A list of Payload objects
  292. """
  293. q = self._new_queue(queue)
  294. return [self._message_to_python(m, queue, q) for m in messages]
  295. def _get_bulk(self, queue, max_if_unlimited=SQS_MAX_MESSAGES):
  296. """Try to retrieve multiple messages off ``queue``.
  297. Where _get() returns a single Payload object, this method returns a
  298. list of Payload objects. The number of objects returned is determined
  299. by the total number of messages available in the queue and the
  300. number of messages that the QoS object allows (based on the
  301. prefetch_count).
  302. .. note::
  303. Ignores QoS limits so caller is responsible for checking
  304. that we are allowed to consume at least one message from the
  305. queue. get_bulk will then ask QoS for an estimate of
  306. the number of extra messages that we can consume.
  307. args:
  308. queue: The queue name (string) to pull from
  309. returns:
  310. payloads: A list of payload objects returned
  311. """
  312. # drain_events calls `can_consume` first, consuming
  313. # a token, so we know that we are allowed to consume at least
  314. # one message.
  315. maxcount = self.qos.can_consume_max_estimate()
  316. maxcount = max_if_unlimited if maxcount is None else max(maxcount, 1)
  317. if maxcount:
  318. messages = self._get_from_sqs(
  319. queue, count=min(maxcount, SQS_MAX_MESSAGES),
  320. )
  321. if messages:
  322. return self._messages_to_python(messages, queue)
  323. raise Empty()
  324. def _get(self, queue):
  325. """Try to retrieve a single message off ``queue``."""
  326. messages = self._get_from_sqs(queue, count=1)
  327. if messages:
  328. return self._messages_to_python(messages, queue)[0]
  329. raise Empty()
  330. def _restore(self, message,
  331. unwanted_delivery_info=('sqs_message', 'sqs_queue')):
  332. for unwanted_key in unwanted_delivery_info:
  333. # Remove objects that aren't JSON serializable (Issue #1108).
  334. message.delivery_info.pop(unwanted_key, None)
  335. return super(Channel, self)._restore(message)
  336. def basic_ack(self, delivery_tag):
  337. delivery_info = self.qos.get(delivery_tag).delivery_info
  338. try:
  339. queue = delivery_info['sqs_queue']
  340. except KeyError:
  341. pass
  342. else:
  343. queue.delete_message(delivery_info['sqs_message'])
  344. super(Channel, self).basic_ack(delivery_tag)
  345. def _size(self, queue):
  346. """Return the number of messages in a queue."""
  347. return self._new_queue(queue).count()
  348. def _purge(self, queue):
  349. """Delete all current messages in a queue."""
  350. q = self._new_queue(queue)
  351. # SQS is slow at registering messages, so run for a few
  352. # iterations to ensure messages are deleted.
  353. size = 0
  354. for i in range(10):
  355. size += q.count()
  356. if not size:
  357. break
  358. q.clear()
  359. return size
  360. def close(self):
  361. super(Channel, self).close()
  362. for conn in (self._sqs, self._sdb):
  363. if conn:
  364. try:
  365. conn.close()
  366. except AttributeError as exc: # FIXME ???
  367. if "can't set attribute" not in str(exc):
  368. raise
  369. def _get_regioninfo(self, regions):
  370. if self.region:
  371. for _r in regions:
  372. if _r.name == self.region:
  373. return _r
  374. def _aws_connect_to(self, fun, regions):
  375. conninfo = self.conninfo
  376. region = self._get_regioninfo(regions)
  377. return fun(region=region,
  378. aws_access_key_id=conninfo.userid,
  379. aws_secret_access_key=conninfo.password,
  380. port=conninfo.port)
  381. @property
  382. def sqs(self):
  383. if self._sqs is None:
  384. self._sqs = self._aws_connect_to(SQSConnection, _sqs.regions())
  385. return self._sqs
  386. @property
  387. def sdb(self):
  388. if self._sdb is None:
  389. self._sdb = self._aws_connect_to(SDBConnection, _sdb.regions())
  390. return self._sdb
  391. @property
  392. def table(self):
  393. name = self.entity_name(
  394. self.domain_format % {'vhost': self.conninfo.virtual_host})
  395. d = self.sdb.get_object(
  396. 'CreateDomain', {'DomainName': name}, self.Table)
  397. d.name = name
  398. return d
  399. @property
  400. def conninfo(self):
  401. return self.connection.client
  402. @property
  403. def transport_options(self):
  404. return self.connection.client.transport_options
  405. @cached_property
  406. def visibility_timeout(self):
  407. return (self.transport_options.get('visibility_timeout') or
  408. self.default_visibility_timeout)
  409. @cached_property
  410. def queue_name_prefix(self):
  411. return self.transport_options.get('queue_name_prefix', '')
  412. @cached_property
  413. def supports_fanout(self):
  414. return self.transport_options.get('sdb_persistence', False)
  415. @cached_property
  416. def region(self):
  417. return self.transport_options.get('region') or self.default_region
  418. @cached_property
  419. def wait_time_seconds(self):
  420. return self.transport_options.get('wait_time_seconds',
  421. self.default_wait_time_seconds)
  422. class Transport(virtual.Transport):
  423. Channel = Channel
  424. polling_interval = 1
  425. wait_time_seconds = 0
  426. default_port = None
  427. connection_errors = (
  428. virtual.Transport.connection_errors +
  429. (exception.SQSError, socket.error)
  430. )
  431. channel_errors = (
  432. virtual.Transport.channel_errors + (exception.SQSDecodeError, )
  433. )
  434. driver_type = 'sqs'
  435. driver_name = 'sqs'