http2_base_server.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # Copyright 2016 gRPC authors.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import struct
  16. import h2
  17. import h2.connection
  18. import messages_pb2
  19. import twisted
  20. import twisted.internet
  21. import twisted.internet.protocol
  22. _READ_CHUNK_SIZE = 16384
  23. _GRPC_HEADER_SIZE = 5
  24. _MIN_SETTINGS_MAX_FRAME_SIZE = 16384
  25. class H2ProtocolBaseServer(twisted.internet.protocol.Protocol):
  26. def __init__(self):
  27. self._conn = h2.connection.H2Connection(client_side=False)
  28. self._recv_buffer = {}
  29. self._handlers = {}
  30. self._handlers['ConnectionMade'] = self.on_connection_made_default
  31. self._handlers['DataReceived'] = self.on_data_received_default
  32. self._handlers['WindowUpdated'] = self.on_window_update_default
  33. self._handlers['RequestReceived'] = self.on_request_received_default
  34. self._handlers['SendDone'] = self.on_send_done_default
  35. self._handlers['ConnectionLost'] = self.on_connection_lost
  36. self._handlers['PingAcknowledged'] = self.on_ping_acknowledged_default
  37. self._stream_status = {}
  38. self._send_remaining = {}
  39. self._outstanding_pings = 0
  40. def set_handlers(self, handlers):
  41. self._handlers = handlers
  42. def connectionMade(self):
  43. self._handlers['ConnectionMade']()
  44. def connectionLost(self, reason):
  45. self._handlers['ConnectionLost'](reason)
  46. def on_connection_made_default(self):
  47. logging.info('Connection Made')
  48. self._conn.initiate_connection()
  49. self.transport.setTcpNoDelay(True)
  50. self.transport.write(self._conn.data_to_send())
  51. def on_connection_lost(self, reason):
  52. logging.info('Disconnected %s' % reason)
  53. def dataReceived(self, data):
  54. try:
  55. events = self._conn.receive_data(data)
  56. except h2.exceptions.ProtocolError:
  57. # this try/except block catches exceptions due to race between sending
  58. # GOAWAY and processing a response in flight.
  59. return
  60. if self._conn.data_to_send:
  61. self.transport.write(self._conn.data_to_send())
  62. for event in events:
  63. if isinstance(event, h2.events.RequestReceived
  64. ) and self._handlers.has_key('RequestReceived'):
  65. logging.info('RequestReceived Event for stream: %d' %
  66. event.stream_id)
  67. self._handlers['RequestReceived'](event)
  68. elif isinstance(event, h2.events.DataReceived
  69. ) and self._handlers.has_key('DataReceived'):
  70. logging.info('DataReceived Event for stream: %d' %
  71. event.stream_id)
  72. self._handlers['DataReceived'](event)
  73. elif isinstance(event, h2.events.WindowUpdated
  74. ) and self._handlers.has_key('WindowUpdated'):
  75. logging.info('WindowUpdated Event for stream: %d' %
  76. event.stream_id)
  77. self._handlers['WindowUpdated'](event)
  78. elif isinstance(event, h2.events.PingAcknowledged
  79. ) and self._handlers.has_key('PingAcknowledged'):
  80. logging.info('PingAcknowledged Event')
  81. self._handlers['PingAcknowledged'](event)
  82. self.transport.write(self._conn.data_to_send())
  83. def on_ping_acknowledged_default(self, event):
  84. logging.info('ping acknowledged')
  85. self._outstanding_pings -= 1
  86. def on_data_received_default(self, event):
  87. self._conn.acknowledge_received_data(len(event.data), event.stream_id)
  88. self._recv_buffer[event.stream_id] += event.data
  89. def on_request_received_default(self, event):
  90. self._recv_buffer[event.stream_id] = ''
  91. self._stream_id = event.stream_id
  92. self._stream_status[event.stream_id] = True
  93. self._conn.send_headers(
  94. stream_id=event.stream_id,
  95. headers=[
  96. (':status', '200'),
  97. ('content-type', 'application/grpc'),
  98. ('grpc-encoding', 'identity'),
  99. ('grpc-accept-encoding', 'identity,deflate,gzip'),
  100. ],
  101. )
  102. self.transport.write(self._conn.data_to_send())
  103. def on_window_update_default(self,
  104. _,
  105. pad_length=None,
  106. read_chunk_size=_READ_CHUNK_SIZE):
  107. # try to resume sending on all active streams (update might be for connection)
  108. for stream_id in self._send_remaining:
  109. self.default_send(stream_id,
  110. pad_length=pad_length,
  111. read_chunk_size=read_chunk_size)
  112. def send_reset_stream(self):
  113. self._conn.reset_stream(self._stream_id)
  114. self.transport.write(self._conn.data_to_send())
  115. def setup_send(self,
  116. data_to_send,
  117. stream_id,
  118. pad_length=None,
  119. read_chunk_size=_READ_CHUNK_SIZE):
  120. logging.info('Setting up data to send for stream_id: %d' % stream_id)
  121. self._send_remaining[stream_id] = len(data_to_send)
  122. self._send_offset = 0
  123. self._data_to_send = data_to_send
  124. self.default_send(stream_id,
  125. pad_length=pad_length,
  126. read_chunk_size=read_chunk_size)
  127. def default_send(self,
  128. stream_id,
  129. pad_length=None,
  130. read_chunk_size=_READ_CHUNK_SIZE):
  131. if not self._send_remaining.has_key(stream_id):
  132. # not setup to send data yet
  133. return
  134. while self._send_remaining[stream_id] > 0:
  135. lfcw = self._conn.local_flow_control_window(stream_id)
  136. padding_bytes = pad_length + 1 if pad_length is not None else 0
  137. if lfcw - padding_bytes <= 0:
  138. logging.info(
  139. 'Stream %d. lfcw: %d. padding bytes: %d. not enough quota yet'
  140. % (stream_id, lfcw, padding_bytes))
  141. break
  142. chunk_size = min(lfcw - padding_bytes, read_chunk_size)
  143. bytes_to_send = min(chunk_size, self._send_remaining[stream_id])
  144. logging.info(
  145. 'flow_control_window = %d. sending [%d:%d] stream_id %d. includes %d total padding bytes'
  146. % (lfcw, self._send_offset, self._send_offset + bytes_to_send +
  147. padding_bytes, stream_id, padding_bytes))
  148. # The receiver might allow sending frames larger than the http2 minimum
  149. # max frame size (16384), but this test should never send more than 16384
  150. # for simplicity (which is always legal).
  151. if bytes_to_send + padding_bytes > _MIN_SETTINGS_MAX_FRAME_SIZE:
  152. raise ValueError("overload: sending %d" %
  153. (bytes_to_send + padding_bytes))
  154. data = self._data_to_send[self._send_offset:self._send_offset +
  155. bytes_to_send]
  156. try:
  157. self._conn.send_data(stream_id,
  158. data,
  159. end_stream=False,
  160. pad_length=pad_length)
  161. except h2.exceptions.ProtocolError:
  162. logging.info('Stream %d is closed' % stream_id)
  163. break
  164. self._send_remaining[stream_id] -= bytes_to_send
  165. self._send_offset += bytes_to_send
  166. if self._send_remaining[stream_id] == 0:
  167. self._handlers['SendDone'](stream_id)
  168. def default_ping(self):
  169. logging.info('sending ping')
  170. self._outstanding_pings += 1
  171. self._conn.ping(b'\x00' * 8)
  172. self.transport.write(self._conn.data_to_send())
  173. def on_send_done_default(self, stream_id):
  174. if self._stream_status[stream_id]:
  175. self._stream_status[stream_id] = False
  176. self.default_send_trailer(stream_id)
  177. else:
  178. logging.error('Stream %d is already closed' % stream_id)
  179. def default_send_trailer(self, stream_id):
  180. logging.info('Sending trailer for stream id %d' % stream_id)
  181. self._conn.send_headers(stream_id,
  182. headers=[('grpc-status', '0')],
  183. end_stream=True)
  184. self.transport.write(self._conn.data_to_send())
  185. @staticmethod
  186. def default_response_data(response_size):
  187. sresp = messages_pb2.SimpleResponse()
  188. sresp.payload.body = b'\x00' * response_size
  189. serialized_resp_proto = sresp.SerializeToString()
  190. response_data = b'\x00' + struct.pack(
  191. 'i', len(serialized_resp_proto))[::-1] + serialized_resp_proto
  192. return response_data
  193. def parse_received_data(self, stream_id):
  194. """ returns a grpc framed string of bytes containing response proto of the size
  195. asked in request """
  196. recv_buffer = self._recv_buffer[stream_id]
  197. grpc_msg_size = struct.unpack('i', recv_buffer[1:5][::-1])[0]
  198. if len(recv_buffer) != _GRPC_HEADER_SIZE + grpc_msg_size:
  199. return None
  200. req_proto_str = recv_buffer[5:5 + grpc_msg_size]
  201. sr = messages_pb2.SimpleRequest()
  202. sr.ParseFromString(req_proto_str)
  203. logging.info('Parsed simple request for stream %d' % stream_id)
  204. return sr