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.

method_framing.py 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. """Convert between frames and higher-level AMQP methods"""
  2. # Copyright (C) 2007-2008 Barry Pederson <bp@barryp.org>
  3. #
  4. # This library is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU Lesser General Public
  6. # License as published by the Free Software Foundation; either
  7. # version 2.1 of the License, or (at your option) any later version.
  8. #
  9. # This library is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. # Lesser General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Lesser General Public
  15. # License along with this library; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
  17. from __future__ import absolute_import
  18. from collections import defaultdict, deque
  19. from struct import pack, unpack
  20. from .basic_message import Message
  21. from .exceptions import AMQPError, UnexpectedFrame
  22. from .five import range, string
  23. from .serialization import AMQPReader
  24. __all__ = ['MethodReader']
  25. #
  26. # MethodReader needs to know which methods are supposed
  27. # to be followed by content headers and bodies.
  28. #
  29. _CONTENT_METHODS = [
  30. (60, 50), # Basic.return
  31. (60, 60), # Basic.deliver
  32. (60, 71), # Basic.get_ok
  33. ]
  34. class _PartialMessage(object):
  35. """Helper class to build up a multi-frame method."""
  36. def __init__(self, method_sig, args, channel):
  37. self.method_sig = method_sig
  38. self.args = args
  39. self.msg = Message()
  40. self.body_parts = []
  41. self.body_received = 0
  42. self.body_size = None
  43. self.complete = False
  44. def add_header(self, payload):
  45. class_id, weight, self.body_size = unpack('>HHQ', payload[:12])
  46. self.msg._load_properties(payload[12:])
  47. self.complete = (self.body_size == 0)
  48. def add_payload(self, payload):
  49. parts = self.body_parts
  50. self.body_received += len(payload)
  51. if self.body_received == self.body_size:
  52. if parts:
  53. parts.append(payload)
  54. self.msg.body = bytes().join(parts)
  55. else:
  56. self.msg.body = payload
  57. self.complete = True
  58. else:
  59. parts.append(payload)
  60. class MethodReader(object):
  61. """Helper class to receive frames from the broker, combine them if
  62. necessary with content-headers and content-bodies into complete methods.
  63. Normally a method is represented as a tuple containing
  64. (channel, method_sig, args, content).
  65. In the case of a framing error, an :exc:`ConnectionError` is placed
  66. in the queue.
  67. In the case of unexpected frames, a tuple made up of
  68. ``(channel, ChannelError)`` is placed in the queue.
  69. """
  70. def __init__(self, source):
  71. self.source = source
  72. self.queue = deque()
  73. self.running = False
  74. self.partial_messages = {}
  75. self.heartbeats = 0
  76. # For each channel, which type is expected next
  77. self.expected_types = defaultdict(lambda: 1)
  78. # not an actual byte count, just incremented whenever we receive
  79. self.bytes_recv = 0
  80. self._quick_put = self.queue.append
  81. self._quick_get = self.queue.popleft
  82. def _next_method(self):
  83. """Read the next method from the source, once one complete method has
  84. been assembled it is placed in the internal queue."""
  85. queue = self.queue
  86. put = self._quick_put
  87. read_frame = self.source.read_frame
  88. while not queue:
  89. try:
  90. frame_type, channel, payload = read_frame()
  91. except Exception as exc:
  92. #
  93. # Connection was closed? Framing Error?
  94. #
  95. put(exc)
  96. break
  97. self.bytes_recv += 1
  98. if frame_type not in (self.expected_types[channel], 8):
  99. put((
  100. channel,
  101. UnexpectedFrame(
  102. 'Received frame {0} while expecting type: {1}'.format(
  103. frame_type, self.expected_types[channel]))))
  104. elif frame_type == 1:
  105. self._process_method_frame(channel, payload)
  106. elif frame_type == 2:
  107. self._process_content_header(channel, payload)
  108. elif frame_type == 3:
  109. self._process_content_body(channel, payload)
  110. elif frame_type == 8:
  111. self._process_heartbeat(channel, payload)
  112. def _process_heartbeat(self, channel, payload):
  113. self.heartbeats += 1
  114. def _process_method_frame(self, channel, payload):
  115. """Process Method frames"""
  116. method_sig = unpack('>HH', payload[:4])
  117. args = AMQPReader(payload[4:])
  118. if method_sig in _CONTENT_METHODS:
  119. #
  120. # Save what we've got so far and wait for the content-header
  121. #
  122. self.partial_messages[channel] = _PartialMessage(
  123. method_sig, args, channel,
  124. )
  125. self.expected_types[channel] = 2
  126. else:
  127. self._quick_put((channel, method_sig, args, None))
  128. def _process_content_header(self, channel, payload):
  129. """Process Content Header frames"""
  130. partial = self.partial_messages[channel]
  131. partial.add_header(payload)
  132. if partial.complete:
  133. #
  134. # a bodyless message, we're done
  135. #
  136. self._quick_put((channel, partial.method_sig,
  137. partial.args, partial.msg))
  138. self.partial_messages.pop(channel, None)
  139. self.expected_types[channel] = 1
  140. else:
  141. #
  142. # wait for the content-body
  143. #
  144. self.expected_types[channel] = 3
  145. def _process_content_body(self, channel, payload):
  146. """Process Content Body frames"""
  147. partial = self.partial_messages[channel]
  148. partial.add_payload(payload)
  149. if partial.complete:
  150. #
  151. # Stick the message in the queue and go back to
  152. # waiting for method frames
  153. #
  154. self._quick_put((channel, partial.method_sig,
  155. partial.args, partial.msg))
  156. self.partial_messages.pop(channel, None)
  157. self.expected_types[channel] = 1
  158. def read_method(self):
  159. """Read a method from the peer."""
  160. self._next_method()
  161. m = self._quick_get()
  162. if isinstance(m, Exception):
  163. raise m
  164. if isinstance(m, tuple) and isinstance(m[1], AMQPError):
  165. raise m[1]
  166. return m
  167. class MethodWriter(object):
  168. """Convert AMQP methods into AMQP frames and send them out
  169. to the peer."""
  170. def __init__(self, dest, frame_max):
  171. self.dest = dest
  172. self.frame_max = frame_max
  173. self.bytes_sent = 0
  174. def write_method(self, channel, method_sig, args, content=None):
  175. write_frame = self.dest.write_frame
  176. payload = pack('>HH', method_sig[0], method_sig[1]) + args
  177. if content:
  178. # do this early, so we can raise an exception if there's a
  179. # problem with the content properties, before sending the
  180. # first frame
  181. body = content.body
  182. if isinstance(body, string):
  183. coding = content.properties.get('content_encoding', None)
  184. if coding is None:
  185. coding = content.properties['content_encoding'] = 'UTF-8'
  186. body = body.encode(coding)
  187. properties = content._serialize_properties()
  188. write_frame(1, channel, payload)
  189. if content:
  190. payload = pack('>HHQ', method_sig[0], 0, len(body)) + properties
  191. write_frame(2, channel, payload)
  192. chunk_size = self.frame_max - 8
  193. for i in range(0, len(body), chunk_size):
  194. write_frame(3, channel, body[i:i + chunk_size])
  195. self.bytes_sent += 1