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.

200 lines
5.6 KiB

  1. import socket
  2. import select
  3. import sys
  4. import os
  5. from wire import *
  6. from reader import *
  7. from msg import *
  8. # hold the asyncronous state of a connection
  9. # ie. we may not get enough bytes on one read to decode the message
  10. class Connection():
  11. def __init__(self, fd, appCtx):
  12. self.fd = fd
  13. self.appCtx = appCtx
  14. self.recBuf = BytesBuffer(bytearray())
  15. self.resBuf = BytesBuffer(bytearray())
  16. self.msgLength = 0
  17. self.decoder = RequestDecoder(self.recBuf)
  18. self.inProgress = False # are we in the middle of a message
  19. def recv(this):
  20. data = this.fd.recv(1024)
  21. if not data: # what about len(data) == 0
  22. raise IOError("dead connection")
  23. this.recBuf.write(data)
  24. # TMSP server responds to messges by calling methods on the app
  25. class TMSPServer():
  26. def __init__(self, app, port=5410):
  27. self.app = app
  28. self.appMap = {} # map conn file descriptors to (appContext, reqBuf, resBuf, msgDecoder)
  29. self.port = port
  30. self.listen_backlog = 10
  31. self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  32. self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  33. self.listener.setblocking(0)
  34. self.listener.bind(('', port))
  35. self.listener.listen(self.listen_backlog)
  36. self.shutdown = False
  37. self.read_list = [self.listener]
  38. self.write_list = []
  39. def handle_new_connection(self, r):
  40. new_fd, new_addr = r.accept()
  41. new_fd.setblocking(0) # non-blocking
  42. self.read_list.append(new_fd)
  43. self.write_list.append(new_fd)
  44. print 'new connection to', new_addr
  45. appContext = self.app.open()
  46. self.appMap[new_fd] = Connection(new_fd, appContext)
  47. def handle_conn_closed(self, r):
  48. self.read_list.remove(r)
  49. self.write_list.remove(r)
  50. r.close()
  51. print "connection closed"
  52. def handle_recv(self, r):
  53. # appCtx, recBuf, resBuf, conn
  54. conn = self.appMap[r]
  55. while True:
  56. try:
  57. print "recv loop"
  58. # check if we need more data first
  59. if conn.inProgress:
  60. if conn.msgLength == 0 or conn.recBuf.size() < conn.msgLength:
  61. conn.recv()
  62. else:
  63. if conn.recBuf.size() == 0:
  64. conn.recv()
  65. conn.inProgress = True
  66. # see if we have enough to get the message length
  67. if conn.msgLength == 0:
  68. ll = conn.recBuf.peek()
  69. if conn.recBuf.size() < 1 + ll:
  70. # we don't have enough bytes to read the length yet
  71. return
  72. print "decoding msg length"
  73. conn.msgLength = decode_varint(conn.recBuf)
  74. # see if we have enough to decode the message
  75. if conn.recBuf.size() < conn.msgLength:
  76. return
  77. # now we can decode the message
  78. # first read the request type and get the particular msg decoder
  79. typeByte = conn.recBuf.read(1)
  80. typeByte = int(typeByte[0])
  81. resTypeByte = typeByte+0x10
  82. req_type = message_types[typeByte]
  83. if req_type == "flush":
  84. # messages are length prefixed
  85. conn.resBuf.write(encode(1))
  86. conn.resBuf.write([resTypeByte])
  87. sent = conn.fd.send(str(conn.resBuf.buf))
  88. conn.msgLength = 0
  89. conn.inProgress = False
  90. conn.resBuf = BytesBuffer(bytearray())
  91. return
  92. decoder = getattr(conn.decoder, req_type)
  93. print "decoding args"
  94. req_args = decoder()
  95. print "got args", req_args
  96. # done decoding message
  97. conn.msgLength = 0
  98. conn.inProgress = False
  99. req_f = getattr(conn.appCtx, req_type)
  100. if req_args == None:
  101. res = req_f()
  102. elif isinstance(req_args, tuple):
  103. res = req_f(*req_args)
  104. else:
  105. res = req_f(req_args)
  106. if isinstance(res, tuple):
  107. res, ret_code = res
  108. else:
  109. ret_code = res
  110. res = None
  111. print "called", req_type, "ret code:", ret_code
  112. if ret_code != 0:
  113. print "non-zero retcode:", ret_code
  114. if req_type in ("echo", "info"): # these dont return a ret code
  115. enc = encode(res)
  116. # messages are length prefixed
  117. conn.resBuf.write(encode(len(enc) + 1))
  118. conn.resBuf.write([resTypeByte])
  119. conn.resBuf.write(enc)
  120. else:
  121. enc, encRet = encode(res), encode(ret_code)
  122. # messages are length prefixed
  123. conn.resBuf.write(encode(len(enc)+len(encRet)+1))
  124. conn.resBuf.write([resTypeByte])
  125. conn.resBuf.write(encRet)
  126. conn.resBuf.write(enc)
  127. except TypeError as e:
  128. print "TypeError on reading from connection:", e
  129. self.handle_conn_closed(r)
  130. return
  131. except ValueError as e:
  132. print "ValueError on reading from connection:", e
  133. self.handle_conn_closed(r)
  134. return
  135. except IOError as e:
  136. print "IOError on reading from connection:", e
  137. self.handle_conn_closed(r)
  138. return
  139. except Exception as e:
  140. print "error reading from connection", str(e) # sys.exc_info()[0] # TODO better
  141. self.handle_conn_closed(r)
  142. return
  143. def main_loop(self):
  144. while not self.shutdown:
  145. r_list, w_list, _ = select.select(self.read_list, self.write_list, [], 2.5)
  146. for r in r_list:
  147. if (r == self.listener):
  148. try:
  149. self.handle_new_connection(r)
  150. # undo adding to read list ...
  151. except rameError as e:
  152. print "Could not connect due to NameError:", e
  153. except TypeError as e:
  154. print "Could not connect due to TypeError:", e
  155. except:
  156. print "Could not connect due to unexpected error:", sys.exc_info()[0]
  157. else:
  158. self.handle_recv(r)
  159. def handle_shutdown(self):
  160. for r in self.read_list:
  161. r.close()
  162. for w in self.write_list:
  163. try:
  164. w.close()
  165. except: pass
  166. self.shutdown = True