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.

__init__.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. """
  2. kombu.transport.virtual
  3. =======================
  4. Virtual transport implementation.
  5. Emulates the AMQ API for non-AMQ transports.
  6. """
  7. from __future__ import absolute_import, unicode_literals
  8. import base64
  9. import socket
  10. import sys
  11. import warnings
  12. from array import array
  13. from itertools import count
  14. from multiprocessing.util import Finalize
  15. from time import sleep
  16. from amqp.protocol import queue_declare_ok_t
  17. from kombu.exceptions import ResourceError, ChannelError
  18. from kombu.five import Empty, items, monotonic
  19. from kombu.utils import emergency_dump_state, kwdict, say, uuid
  20. from kombu.utils.compat import OrderedDict
  21. from kombu.utils.encoding import str_to_bytes, bytes_to_str
  22. from kombu.transport import base
  23. from .scheduling import FairCycle
  24. from .exchange import STANDARD_EXCHANGE_TYPES
  25. ARRAY_TYPE_H = 'H' if sys.version_info[0] == 3 else b'H'
  26. UNDELIVERABLE_FMT = """\
  27. Message could not be delivered: No queues bound to exchange {exchange!r} \
  28. using binding key {routing_key!r}.
  29. """
  30. NOT_EQUIVALENT_FMT = """\
  31. Cannot redeclare exchange {0!r} in vhost {1!r} with \
  32. different type, durable, autodelete or arguments value.\
  33. """
  34. class Base64(object):
  35. def encode(self, s):
  36. return bytes_to_str(base64.b64encode(str_to_bytes(s)))
  37. def decode(self, s):
  38. return base64.b64decode(str_to_bytes(s))
  39. class NotEquivalentError(Exception):
  40. """Entity declaration is not equivalent to the previous declaration."""
  41. pass
  42. class UndeliverableWarning(UserWarning):
  43. """The message could not be delivered to a queue."""
  44. pass
  45. class BrokerState(object):
  46. #: exchange declarations.
  47. exchanges = None
  48. #: active bindings.
  49. bindings = None
  50. def __init__(self, exchanges=None, bindings=None):
  51. self.exchanges = {} if exchanges is None else exchanges
  52. self.bindings = {} if bindings is None else bindings
  53. def clear(self):
  54. self.exchanges.clear()
  55. self.bindings.clear()
  56. class QoS(object):
  57. """Quality of Service guarantees.
  58. Only supports `prefetch_count` at this point.
  59. :param channel: AMQ Channel.
  60. :keyword prefetch_count: Initial prefetch count (defaults to 0).
  61. """
  62. #: current prefetch count value
  63. prefetch_count = 0
  64. #: :class:`~collections.OrderedDict` of active messages.
  65. #: *NOTE*: Can only be modified by the consuming thread.
  66. _delivered = None
  67. #: acks can be done by other threads than the consuming thread.
  68. #: Instead of a mutex, which doesn't perform well here, we mark
  69. #: the delivery tags as dirty, so subsequent calls to append() can remove
  70. #: them.
  71. _dirty = None
  72. #: If disabled, unacked messages won't be restored at shutdown.
  73. restore_at_shutdown = True
  74. def __init__(self, channel, prefetch_count=0):
  75. self.channel = channel
  76. self.prefetch_count = prefetch_count or 0
  77. self._delivered = OrderedDict()
  78. self._delivered.restored = False
  79. self._dirty = set()
  80. self._quick_ack = self._dirty.add
  81. self._quick_append = self._delivered.__setitem__
  82. self._on_collect = Finalize(
  83. self, self.restore_unacked_once, exitpriority=1,
  84. )
  85. def can_consume(self):
  86. """Return true if the channel can be consumed from.
  87. Used to ensure the client adhers to currently active
  88. prefetch limits.
  89. """
  90. pcount = self.prefetch_count
  91. return not pcount or len(self._delivered) - len(self._dirty) < pcount
  92. def can_consume_max_estimate(self):
  93. """Returns the maximum number of messages allowed to be returned.
  94. Returns an estimated number of messages that a consumer may be allowed
  95. to consume at once from the broker. This is used for services where
  96. bulk 'get message' calls are preferred to many individual 'get message'
  97. calls - like SQS.
  98. returns:
  99. An integer > 0
  100. """
  101. pcount = self.prefetch_count
  102. if pcount:
  103. return max(pcount - (len(self._delivered) - len(self._dirty)), 0)
  104. def append(self, message, delivery_tag):
  105. """Append message to transactional state."""
  106. if self._dirty:
  107. self._flush()
  108. self._quick_append(delivery_tag, message)
  109. def get(self, delivery_tag):
  110. return self._delivered[delivery_tag]
  111. def _flush(self):
  112. """Flush dirty (acked/rejected) tags from."""
  113. dirty = self._dirty
  114. delivered = self._delivered
  115. while 1:
  116. try:
  117. dirty_tag = dirty.pop()
  118. except KeyError:
  119. break
  120. delivered.pop(dirty_tag, None)
  121. def ack(self, delivery_tag):
  122. """Acknowledge message and remove from transactional state."""
  123. self._quick_ack(delivery_tag)
  124. def reject(self, delivery_tag, requeue=False):
  125. """Remove from transactional state and requeue message."""
  126. if requeue:
  127. self.channel._restore_at_beginning(self._delivered[delivery_tag])
  128. self._quick_ack(delivery_tag)
  129. def restore_unacked(self):
  130. """Restore all unacknowledged messages."""
  131. self._flush()
  132. delivered = self._delivered
  133. errors = []
  134. restore = self.channel._restore
  135. pop_message = delivered.popitem
  136. while delivered:
  137. try:
  138. _, message = pop_message()
  139. except KeyError: # pragma: no cover
  140. break
  141. try:
  142. restore(message)
  143. except BaseException as exc:
  144. errors.append((exc, message))
  145. delivered.clear()
  146. return errors
  147. def restore_unacked_once(self):
  148. """Restores all unacknowledged messages at shutdown/gc collect.
  149. Will only be done once for each instance.
  150. """
  151. self._on_collect.cancel()
  152. self._flush()
  153. state = self._delivered
  154. if not self.restore_at_shutdown or not self.channel.do_restore:
  155. return
  156. if getattr(state, 'restored', None):
  157. assert not state
  158. return
  159. try:
  160. if state:
  161. say('Restoring {0!r} unacknowledged message(s).',
  162. len(self._delivered))
  163. unrestored = self.restore_unacked()
  164. if unrestored:
  165. errors, messages = list(zip(*unrestored))
  166. say('UNABLE TO RESTORE {0} MESSAGES: {1}',
  167. len(errors), errors)
  168. emergency_dump_state(messages)
  169. finally:
  170. state.restored = True
  171. def restore_visible(self, *args, **kwargs):
  172. """Restore any pending unackwnowledged messages for visibility_timeout
  173. style implementations.
  174. Optional: Currently only used by the Redis transport.
  175. """
  176. pass
  177. class Message(base.Message):
  178. def __init__(self, channel, payload, **kwargs):
  179. self._raw = payload
  180. properties = payload['properties']
  181. body = payload.get('body')
  182. if body:
  183. body = channel.decode_body(body, properties.get('body_encoding'))
  184. kwargs.update({
  185. 'body': body,
  186. 'delivery_tag': properties['delivery_tag'],
  187. 'content_type': payload.get('content-type'),
  188. 'content_encoding': payload.get('content-encoding'),
  189. 'headers': payload.get('headers'),
  190. 'properties': properties,
  191. 'delivery_info': properties.get('delivery_info'),
  192. 'postencode': 'utf-8',
  193. })
  194. super(Message, self).__init__(channel, **kwdict(kwargs))
  195. def serializable(self):
  196. props = self.properties
  197. body, _ = self.channel.encode_body(self.body,
  198. props.get('body_encoding'))
  199. headers = dict(self.headers)
  200. # remove compression header
  201. headers.pop('compression', None)
  202. return {
  203. 'body': body,
  204. 'properties': props,
  205. 'content-type': self.content_type,
  206. 'content-encoding': self.content_encoding,
  207. 'headers': headers,
  208. }
  209. class AbstractChannel(object):
  210. """This is an abstract class defining the channel methods
  211. you'd usually want to implement in a virtual channel.
  212. Do not subclass directly, but rather inherit from :class:`Channel`
  213. instead.
  214. """
  215. def _get(self, queue, timeout=None):
  216. """Get next message from `queue`."""
  217. raise NotImplementedError('Virtual channels must implement _get')
  218. def _put(self, queue, message):
  219. """Put `message` onto `queue`."""
  220. raise NotImplementedError('Virtual channels must implement _put')
  221. def _purge(self, queue):
  222. """Remove all messages from `queue`."""
  223. raise NotImplementedError('Virtual channels must implement _purge')
  224. def _size(self, queue):
  225. """Return the number of messages in `queue` as an :class:`int`."""
  226. return 0
  227. def _delete(self, queue, *args, **kwargs):
  228. """Delete `queue`.
  229. This just purges the queue, if you need to do more you can
  230. override this method.
  231. """
  232. self._purge(queue)
  233. def _new_queue(self, queue, **kwargs):
  234. """Create new queue.
  235. Your transport can override this method if it needs
  236. to do something whenever a new queue is declared.
  237. """
  238. pass
  239. def _has_queue(self, queue, **kwargs):
  240. """Verify that queue exists.
  241. Should return :const:`True` if the queue exists or :const:`False`
  242. otherwise.
  243. """
  244. return True
  245. def _poll(self, cycle, timeout=None):
  246. """Poll a list of queues for available messages."""
  247. return cycle.get()
  248. class Channel(AbstractChannel, base.StdChannel):
  249. """Virtual channel.
  250. :param connection: The transport instance this channel is part of.
  251. """
  252. #: message class used.
  253. Message = Message
  254. #: QoS class used.
  255. QoS = QoS
  256. #: flag to restore unacked messages when channel
  257. #: goes out of scope.
  258. do_restore = True
  259. #: mapping of exchange types and corresponding classes.
  260. exchange_types = dict(STANDARD_EXCHANGE_TYPES)
  261. #: flag set if the channel supports fanout exchanges.
  262. supports_fanout = False
  263. #: Binary <-> ASCII codecs.
  264. codecs = {'base64': Base64()}
  265. #: Default body encoding.
  266. #: NOTE: ``transport_options['body_encoding']`` will override this value.
  267. body_encoding = 'base64'
  268. #: counter used to generate delivery tags for this channel.
  269. _delivery_tags = count(1)
  270. #: Optional queue where messages with no route is delivered.
  271. #: Set by ``transport_options['deadletter_queue']``.
  272. deadletter_queue = None
  273. # List of options to transfer from :attr:`transport_options`.
  274. from_transport_options = ('body_encoding', 'deadletter_queue')
  275. def __init__(self, connection, **kwargs):
  276. self.connection = connection
  277. self._consumers = set()
  278. self._cycle = None
  279. self._tag_to_queue = {}
  280. self._active_queues = []
  281. self._qos = None
  282. self.closed = False
  283. # instantiate exchange types
  284. self.exchange_types = dict(
  285. (typ, cls(self)) for typ, cls in items(self.exchange_types)
  286. )
  287. try:
  288. self.channel_id = self.connection._avail_channel_ids.pop()
  289. except IndexError:
  290. raise ResourceError(
  291. 'No free channel ids, current={0}, channel_max={1}'.format(
  292. len(self.connection.channels),
  293. self.connection.channel_max), (20, 10),
  294. )
  295. topts = self.connection.client.transport_options
  296. for opt_name in self.from_transport_options:
  297. try:
  298. setattr(self, opt_name, topts[opt_name])
  299. except KeyError:
  300. pass
  301. def exchange_declare(self, exchange=None, type='direct', durable=False,
  302. auto_delete=False, arguments=None,
  303. nowait=False, passive=False):
  304. """Declare exchange."""
  305. type = type or 'direct'
  306. exchange = exchange or 'amq.%s' % type
  307. if passive:
  308. if exchange not in self.state.exchanges:
  309. raise ChannelError(
  310. 'NOT_FOUND - no exchange {0!r} in vhost {1!r}'.format(
  311. exchange, self.connection.client.virtual_host or '/'),
  312. (50, 10), 'Channel.exchange_declare', '404',
  313. )
  314. return
  315. try:
  316. prev = self.state.exchanges[exchange]
  317. if not self.typeof(exchange).equivalent(prev, exchange, type,
  318. durable, auto_delete,
  319. arguments):
  320. raise NotEquivalentError(NOT_EQUIVALENT_FMT.format(
  321. exchange, self.connection.client.virtual_host or '/'))
  322. except KeyError:
  323. self.state.exchanges[exchange] = {
  324. 'type': type,
  325. 'durable': durable,
  326. 'auto_delete': auto_delete,
  327. 'arguments': arguments or {},
  328. 'table': [],
  329. }
  330. def exchange_delete(self, exchange, if_unused=False, nowait=False):
  331. """Delete `exchange` and all its bindings."""
  332. for rkey, _, queue in self.get_table(exchange):
  333. self.queue_delete(queue, if_unused=True, if_empty=True)
  334. self.state.exchanges.pop(exchange, None)
  335. def queue_declare(self, queue=None, passive=False, **kwargs):
  336. """Declare queue."""
  337. queue = queue or 'amq.gen-%s' % uuid()
  338. if passive and not self._has_queue(queue, **kwargs):
  339. raise ChannelError(
  340. 'NOT_FOUND - no queue {0!r} in vhost {1!r}'.format(
  341. queue, self.connection.client.virtual_host or '/'),
  342. (50, 10), 'Channel.queue_declare', '404',
  343. )
  344. else:
  345. self._new_queue(queue, **kwargs)
  346. return queue_declare_ok_t(queue, self._size(queue), 0)
  347. def queue_delete(self, queue, if_unused=False, if_empty=False, **kwargs):
  348. """Delete queue."""
  349. if if_empty and self._size(queue):
  350. return
  351. try:
  352. exchange, routing_key, arguments = self.state.bindings[queue]
  353. except KeyError:
  354. return
  355. meta = self.typeof(exchange).prepare_bind(
  356. queue, exchange, routing_key, arguments,
  357. )
  358. self._delete(queue, exchange, *meta)
  359. self.state.bindings.pop(queue, None)
  360. def after_reply_message_received(self, queue):
  361. self.queue_delete(queue)
  362. def exchange_bind(self, destination, source='', routing_key='',
  363. nowait=False, arguments=None):
  364. raise NotImplementedError('transport does not support exchange_bind')
  365. def exchange_unbind(self, destination, source='', routing_key='',
  366. nowait=False, arguments=None):
  367. raise NotImplementedError('transport does not support exchange_unbind')
  368. def queue_bind(self, queue, exchange=None, routing_key='',
  369. arguments=None, **kwargs):
  370. """Bind `queue` to `exchange` with `routing key`."""
  371. if queue in self.state.bindings:
  372. return
  373. exchange = exchange or 'amq.direct'
  374. table = self.state.exchanges[exchange].setdefault('table', [])
  375. self.state.bindings[queue] = exchange, routing_key, arguments
  376. meta = self.typeof(exchange).prepare_bind(
  377. queue, exchange, routing_key, arguments,
  378. )
  379. table.append(meta)
  380. if self.supports_fanout:
  381. self._queue_bind(exchange, *meta)
  382. def queue_unbind(self, queue, exchange=None, routing_key='',
  383. arguments=None, **kwargs):
  384. raise NotImplementedError('transport does not support queue_unbind')
  385. def list_bindings(self):
  386. return ((queue, exchange, rkey)
  387. for exchange in self.state.exchanges
  388. for rkey, pattern, queue in self.get_table(exchange))
  389. def queue_purge(self, queue, **kwargs):
  390. """Remove all ready messages from queue."""
  391. return self._purge(queue)
  392. def _next_delivery_tag(self):
  393. return uuid()
  394. def basic_publish(self, message, exchange, routing_key, **kwargs):
  395. """Publish message."""
  396. message['body'], body_encoding = self.encode_body(
  397. message['body'], self.body_encoding,
  398. )
  399. props = message['properties']
  400. props.update(
  401. body_encoding=body_encoding,
  402. delivery_tag=self._next_delivery_tag(),
  403. )
  404. props['delivery_info'].update(
  405. exchange=exchange,
  406. routing_key=routing_key,
  407. )
  408. if exchange:
  409. return self.typeof(exchange).deliver(
  410. message, exchange, routing_key, **kwargs
  411. )
  412. # anon exchange: routing_key is the destination queue
  413. return self._put(routing_key, message, **kwargs)
  414. def basic_consume(self, queue, no_ack, callback, consumer_tag, **kwargs):
  415. """Consume from `queue`"""
  416. self._tag_to_queue[consumer_tag] = queue
  417. self._active_queues.append(queue)
  418. def _callback(raw_message):
  419. message = self.Message(self, raw_message)
  420. if not no_ack:
  421. self.qos.append(message, message.delivery_tag)
  422. return callback(message)
  423. self.connection._callbacks[queue] = _callback
  424. self._consumers.add(consumer_tag)
  425. self._reset_cycle()
  426. def basic_cancel(self, consumer_tag):
  427. """Cancel consumer by consumer tag."""
  428. if consumer_tag in self._consumers:
  429. self._consumers.remove(consumer_tag)
  430. self._reset_cycle()
  431. queue = self._tag_to_queue.pop(consumer_tag, None)
  432. try:
  433. self._active_queues.remove(queue)
  434. except ValueError:
  435. pass
  436. self.connection._callbacks.pop(queue, None)
  437. def basic_get(self, queue, no_ack=False, **kwargs):
  438. """Get message by direct access (synchronous)."""
  439. try:
  440. message = self.Message(self, self._get(queue))
  441. if not no_ack:
  442. self.qos.append(message, message.delivery_tag)
  443. return message
  444. except Empty:
  445. pass
  446. def basic_ack(self, delivery_tag):
  447. """Acknowledge message."""
  448. self.qos.ack(delivery_tag)
  449. def basic_recover(self, requeue=False):
  450. """Recover unacked messages."""
  451. if requeue:
  452. return self.qos.restore_unacked()
  453. raise NotImplementedError('Does not support recover(requeue=False)')
  454. def basic_reject(self, delivery_tag, requeue=False):
  455. """Reject message."""
  456. self.qos.reject(delivery_tag, requeue=requeue)
  457. def basic_qos(self, prefetch_size=0, prefetch_count=0,
  458. apply_global=False):
  459. """Change QoS settings for this channel.
  460. Only `prefetch_count` is supported.
  461. """
  462. self.qos.prefetch_count = prefetch_count
  463. def get_exchanges(self):
  464. return list(self.state.exchanges)
  465. def get_table(self, exchange):
  466. """Get table of bindings for `exchange`."""
  467. return self.state.exchanges[exchange]['table']
  468. def typeof(self, exchange, default='direct'):
  469. """Get the exchange type instance for `exchange`."""
  470. try:
  471. type = self.state.exchanges[exchange]['type']
  472. except KeyError:
  473. type = default
  474. return self.exchange_types[type]
  475. def _lookup(self, exchange, routing_key, default=None):
  476. """Find all queues matching `routing_key` for the given `exchange`.
  477. Must return the string `default` if no queues matched.
  478. """
  479. if default is None:
  480. default = self.deadletter_queue
  481. try:
  482. R = self.typeof(exchange).lookup(
  483. self.get_table(exchange),
  484. exchange, routing_key, default,
  485. )
  486. except KeyError:
  487. R = []
  488. if not R and default is not None:
  489. warnings.warn(UndeliverableWarning(UNDELIVERABLE_FMT.format(
  490. exchange=exchange, routing_key=routing_key)),
  491. )
  492. self._new_queue(default)
  493. R = [default]
  494. return R
  495. def _restore(self, message):
  496. """Redeliver message to its original destination."""
  497. delivery_info = message.delivery_info
  498. message = message.serializable()
  499. message['redelivered'] = True
  500. for queue in self._lookup(
  501. delivery_info['exchange'], delivery_info['routing_key']):
  502. self._put(queue, message)
  503. def _restore_at_beginning(self, message):
  504. return self._restore(message)
  505. def drain_events(self, timeout=None):
  506. if self._consumers and self.qos.can_consume():
  507. if hasattr(self, '_get_many'):
  508. return self._get_many(self._active_queues, timeout=timeout)
  509. return self._poll(self.cycle, timeout=timeout)
  510. raise Empty()
  511. def message_to_python(self, raw_message):
  512. """Convert raw message to :class:`Message` instance."""
  513. if not isinstance(raw_message, self.Message):
  514. return self.Message(self, payload=raw_message)
  515. return raw_message
  516. def prepare_message(self, body, priority=None, content_type=None,
  517. content_encoding=None, headers=None, properties=None):
  518. """Prepare message data."""
  519. properties = properties or {}
  520. info = properties.setdefault('delivery_info', {})
  521. info['priority'] = priority or 0
  522. return {'body': body,
  523. 'content-encoding': content_encoding,
  524. 'content-type': content_type,
  525. 'headers': headers or {},
  526. 'properties': properties or {}}
  527. def flow(self, active=True):
  528. """Enable/disable message flow.
  529. :raises NotImplementedError: as flow
  530. is not implemented by the base virtual implementation.
  531. """
  532. raise NotImplementedError('virtual channels do not support flow.')
  533. def close(self):
  534. """Close channel, cancel all consumers, and requeue unacked
  535. messages."""
  536. if not self.closed:
  537. self.closed = True
  538. for consumer in list(self._consumers):
  539. self.basic_cancel(consumer)
  540. if self._qos:
  541. self._qos.restore_unacked_once()
  542. if self._cycle is not None:
  543. self._cycle.close()
  544. self._cycle = None
  545. if self.connection is not None:
  546. self.connection.close_channel(self)
  547. self.exchange_types = None
  548. def encode_body(self, body, encoding=None):
  549. if encoding:
  550. return self.codecs.get(encoding).encode(body), encoding
  551. return body, encoding
  552. def decode_body(self, body, encoding=None):
  553. if encoding:
  554. return self.codecs.get(encoding).decode(body)
  555. return body
  556. def _reset_cycle(self):
  557. self._cycle = FairCycle(self._get, self._active_queues, Empty)
  558. def __enter__(self):
  559. return self
  560. def __exit__(self, *exc_info):
  561. self.close()
  562. @property
  563. def state(self):
  564. """Broker state containing exchanges and bindings."""
  565. return self.connection.state
  566. @property
  567. def qos(self):
  568. """:class:`QoS` manager for this channel."""
  569. if self._qos is None:
  570. self._qos = self.QoS(self)
  571. return self._qos
  572. @property
  573. def cycle(self):
  574. if self._cycle is None:
  575. self._reset_cycle()
  576. return self._cycle
  577. class Management(base.Management):
  578. def __init__(self, transport):
  579. super(Management, self).__init__(transport)
  580. self.channel = transport.client.channel()
  581. def get_bindings(self):
  582. return [dict(destination=q, source=e, routing_key=r)
  583. for q, e, r in self.channel.list_bindings()]
  584. def close(self):
  585. self.channel.close()
  586. class Transport(base.Transport):
  587. """Virtual transport.
  588. :param client: :class:`~kombu.Connection` instance
  589. """
  590. Channel = Channel
  591. Cycle = FairCycle
  592. Management = Management
  593. #: :class:`BrokerState` containing declared exchanges and
  594. #: bindings (set by constructor).
  595. state = BrokerState()
  596. #: :class:`~kombu.transport.virtual.scheduling.FairCycle` instance
  597. #: used to fairly drain events from channels (set by constructor).
  598. cycle = None
  599. #: port number used when no port is specified.
  600. default_port = None
  601. #: active channels.
  602. channels = None
  603. #: queue/callback map.
  604. _callbacks = None
  605. #: Time to sleep between unsuccessful polls.
  606. polling_interval = 1.0
  607. #: Max number of channels
  608. channel_max = 65535
  609. def __init__(self, client, **kwargs):
  610. self.client = client
  611. self.channels = []
  612. self._avail_channels = []
  613. self._callbacks = {}
  614. self.cycle = self.Cycle(self._drain_channel, self.channels, Empty)
  615. polling_interval = client.transport_options.get('polling_interval')
  616. if polling_interval is not None:
  617. self.polling_interval = polling_interval
  618. self._avail_channel_ids = array(
  619. ARRAY_TYPE_H, range(self.channel_max, 0, -1),
  620. )
  621. def create_channel(self, connection):
  622. try:
  623. return self._avail_channels.pop()
  624. except IndexError:
  625. channel = self.Channel(connection)
  626. self.channels.append(channel)
  627. return channel
  628. def close_channel(self, channel):
  629. try:
  630. self._avail_channel_ids.append(channel.channel_id)
  631. try:
  632. self.channels.remove(channel)
  633. except ValueError:
  634. pass
  635. finally:
  636. channel.connection = None
  637. def establish_connection(self):
  638. # creates channel to verify connection.
  639. # this channel is then used as the next requested channel.
  640. # (returned by ``create_channel``).
  641. self._avail_channels.append(self.create_channel(self))
  642. return self # for drain events
  643. def close_connection(self, connection):
  644. self.cycle.close()
  645. for l in self._avail_channels, self.channels:
  646. while l:
  647. try:
  648. channel = l.pop()
  649. except (IndexError, KeyError): # pragma: no cover
  650. pass
  651. else:
  652. channel.close()
  653. def drain_events(self, connection, timeout=None):
  654. loop = 0
  655. time_start = monotonic()
  656. get = self.cycle.get
  657. polling_interval = self.polling_interval
  658. while 1:
  659. try:
  660. item, channel = get(timeout=timeout)
  661. except Empty:
  662. if timeout and monotonic() - time_start >= timeout:
  663. raise socket.timeout()
  664. loop += 1
  665. if polling_interval is not None:
  666. sleep(polling_interval)
  667. else:
  668. break
  669. message, queue = item
  670. if not queue or queue not in self._callbacks:
  671. raise KeyError(
  672. 'Message for queue {0!r} without consumers: {1}'.format(
  673. queue, message))
  674. self._callbacks[queue](message)
  675. def _drain_channel(self, channel, timeout=None):
  676. return channel.drain_events(timeout=timeout)
  677. @property
  678. def default_connection_params(self):
  679. return {'port': self.default_port, 'hostname': 'localhost'}