PageRenderTime 42ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/release-0.0.0-rc0/hive/external/service/lib/py/thrift/server/TNonblockingServer.py

#
Python | 309 lines | 246 code | 15 blank | 48 comment | 21 complexity | a3fe5c3abdd08e59501932eee8549f11 MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause, JSON, CPL-1.0
  1. #
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing,
  13. # software distributed under the License is distributed on an
  14. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. # KIND, either express or implied. See the License for the
  16. # specific language governing permissions and limitations
  17. # under the License.
  18. #
  19. """Implementation of non-blocking server.
  20. The main idea of the server is reciving and sending requests
  21. only from main thread.
  22. It also makes thread pool server in tasks terms, not connections.
  23. """
  24. import threading
  25. import socket
  26. import Queue
  27. import select
  28. import struct
  29. import logging
  30. from thrift.transport import TTransport
  31. from thrift.protocol.TBinaryProtocol import TBinaryProtocolFactory
  32. __all__ = ['TNonblockingServer']
  33. class Worker(threading.Thread):
  34. """Worker is a small helper to process incoming connection."""
  35. def __init__(self, queue):
  36. threading.Thread.__init__(self)
  37. self.queue = queue
  38. def run(self):
  39. """Process queries from task queue, stop if processor is None."""
  40. while True:
  41. try:
  42. processor, iprot, oprot, otrans, callback = self.queue.get()
  43. if processor is None:
  44. break
  45. processor.process(iprot, oprot)
  46. callback(True, otrans.getvalue())
  47. except Exception:
  48. logging.exception("Exception while processing request")
  49. callback(False, '')
  50. WAIT_LEN = 0
  51. WAIT_MESSAGE = 1
  52. WAIT_PROCESS = 2
  53. SEND_ANSWER = 3
  54. CLOSED = 4
  55. def locked(func):
  56. "Decorator which locks self.lock."
  57. def nested(self, *args, **kwargs):
  58. self.lock.acquire()
  59. try:
  60. return func(self, *args, **kwargs)
  61. finally:
  62. self.lock.release()
  63. return nested
  64. def socket_exception(func):
  65. "Decorator close object on socket.error."
  66. def read(self, *args, **kwargs):
  67. try:
  68. return func(self, *args, **kwargs)
  69. except socket.error:
  70. self.close()
  71. return read
  72. class Connection:
  73. """Basic class is represented connection.
  74. It can be in state:
  75. WAIT_LEN --- connection is reading request len.
  76. WAIT_MESSAGE --- connection is reading request.
  77. WAIT_PROCESS --- connection has just read whole request and
  78. waits for call ready routine.
  79. SEND_ANSWER --- connection is sending answer string (including length
  80. of answer).
  81. CLOSED --- socket was closed and connection should be deleted.
  82. """
  83. def __init__(self, new_socket, wake_up):
  84. self.socket = new_socket
  85. self.socket.setblocking(False)
  86. self.status = WAIT_LEN
  87. self.len = 0
  88. self.message = ''
  89. self.lock = threading.Lock()
  90. self.wake_up = wake_up
  91. def _read_len(self):
  92. """Reads length of request.
  93. It's really paranoic routine and it may be replaced by
  94. self.socket.recv(4)."""
  95. read = self.socket.recv(4 - len(self.message))
  96. if len(read) == 0:
  97. # if we read 0 bytes and self.message is empty, it means client close
  98. # connection
  99. if len(self.message) != 0:
  100. logging.error("can't read frame size from socket")
  101. self.close()
  102. return
  103. self.message += read
  104. if len(self.message) == 4:
  105. self.len, = struct.unpack('!i', self.message)
  106. if self.len < 0:
  107. logging.error("negative frame size, it seems client"\
  108. " doesn't use FramedTransport")
  109. self.close()
  110. elif self.len == 0:
  111. logging.error("empty frame, it's really strange")
  112. self.close()
  113. else:
  114. self.message = ''
  115. self.status = WAIT_MESSAGE
  116. @socket_exception
  117. def read(self):
  118. """Reads data from stream and switch state."""
  119. assert self.status in (WAIT_LEN, WAIT_MESSAGE)
  120. if self.status == WAIT_LEN:
  121. self._read_len()
  122. # go back to the main loop here for simplicity instead of
  123. # falling through, even though there is a good chance that
  124. # the message is already available
  125. elif self.status == WAIT_MESSAGE:
  126. read = self.socket.recv(self.len - len(self.message))
  127. if len(read) == 0:
  128. logging.error("can't read frame from socket (get %d of %d bytes)" %
  129. (len(self.message), self.len))
  130. self.close()
  131. return
  132. self.message += read
  133. if len(self.message) == self.len:
  134. self.status = WAIT_PROCESS
  135. @socket_exception
  136. def write(self):
  137. """Writes data from socket and switch state."""
  138. assert self.status == SEND_ANSWER
  139. sent = self.socket.send(self.message)
  140. if sent == len(self.message):
  141. self.status = WAIT_LEN
  142. self.message = ''
  143. self.len = 0
  144. else:
  145. self.message = self.message[sent:]
  146. @locked
  147. def ready(self, all_ok, message):
  148. """Callback function for switching state and waking up main thread.
  149. This function is the only function witch can be called asynchronous.
  150. The ready can switch Connection to three states:
  151. WAIT_LEN if request was oneway.
  152. SEND_ANSWER if request was processed in normal way.
  153. CLOSED if request throws unexpected exception.
  154. The one wakes up main thread.
  155. """
  156. assert self.status == WAIT_PROCESS
  157. if not all_ok:
  158. self.close()
  159. self.wake_up()
  160. return
  161. self.len = ''
  162. self.message = struct.pack('!i', len(message)) + message
  163. if len(message) == 0:
  164. # it was a oneway request, do not write answer
  165. self.status = WAIT_LEN
  166. else:
  167. self.status = SEND_ANSWER
  168. self.wake_up()
  169. @locked
  170. def is_writeable(self):
  171. "Returns True if connection should be added to write list of select."
  172. return self.status == SEND_ANSWER
  173. # it's not necessary, but...
  174. @locked
  175. def is_readable(self):
  176. "Returns True if connection should be added to read list of select."
  177. return self.status in (WAIT_LEN, WAIT_MESSAGE)
  178. @locked
  179. def is_closed(self):
  180. "Returns True if connection is closed."
  181. return self.status == CLOSED
  182. def fileno(self):
  183. "Returns the file descriptor of the associated socket."
  184. return self.socket.fileno()
  185. def close(self):
  186. "Closes connection"
  187. self.status = CLOSED
  188. self.socket.close()
  189. class TNonblockingServer:
  190. """Non-blocking server."""
  191. def __init__(self, processor, lsocket, inputProtocolFactory=None,
  192. outputProtocolFactory=None, threads=10):
  193. self.processor = processor
  194. self.socket = lsocket
  195. self.in_protocol = inputProtocolFactory or TBinaryProtocolFactory()
  196. self.out_protocol = outputProtocolFactory or self.in_protocol
  197. self.threads = int(threads)
  198. self.clients = {}
  199. self.tasks = Queue.Queue()
  200. self._read, self._write = socket.socketpair()
  201. self.prepared = False
  202. def setNumThreads(self, num):
  203. """Set the number of worker threads that should be created."""
  204. # implement ThreadPool interface
  205. assert not self.prepared, "You can't change number of threads for working server"
  206. self.threads = num
  207. def prepare(self):
  208. """Prepares server for serve requests."""
  209. self.socket.listen()
  210. for _ in xrange(self.threads):
  211. thread = Worker(self.tasks)
  212. thread.setDaemon(True)
  213. thread.start()
  214. self.prepared = True
  215. def wake_up(self):
  216. """Wake up main thread.
  217. The server usualy waits in select call in we should terminate one.
  218. The simplest way is using socketpair.
  219. Select always wait to read from the first socket of socketpair.
  220. In this case, we can just write anything to the second socket from
  221. socketpair."""
  222. self._write.send('1')
  223. def _select(self):
  224. """Does select on open connections."""
  225. readable = [self.socket.handle.fileno(), self._read.fileno()]
  226. writable = []
  227. for i, connection in self.clients.items():
  228. if connection.is_readable():
  229. readable.append(connection.fileno())
  230. if connection.is_writeable():
  231. writable.append(connection.fileno())
  232. if connection.is_closed():
  233. del self.clients[i]
  234. return select.select(readable, writable, readable)
  235. def handle(self):
  236. """Handle requests.
  237. WARNING! You must call prepare BEFORE calling handle.
  238. """
  239. assert self.prepared, "You have to call prepare before handle"
  240. rset, wset, xset = self._select()
  241. for readable in rset:
  242. if readable == self._read.fileno():
  243. # don't care i just need to clean readable flag
  244. self._read.recv(1024)
  245. elif readable == self.socket.handle.fileno():
  246. client = self.socket.accept().handle
  247. self.clients[client.fileno()] = Connection(client, self.wake_up)
  248. else:
  249. connection = self.clients[readable]
  250. connection.read()
  251. if connection.status == WAIT_PROCESS:
  252. itransport = TTransport.TMemoryBuffer(connection.message)
  253. otransport = TTransport.TMemoryBuffer()
  254. iprot = self.in_protocol.getProtocol(itransport)
  255. oprot = self.out_protocol.getProtocol(otransport)
  256. self.tasks.put([self.processor, iprot, oprot,
  257. otransport, connection.ready])
  258. for writeable in wset:
  259. self.clients[writeable].write()
  260. for oob in xset:
  261. self.clients[oob].close()
  262. del self.clients[oob]
  263. def close(self):
  264. """Closes the server."""
  265. for _ in xrange(self.threads):
  266. self.tasks.put([None, None, None, None, None])
  267. self.socket.close()
  268. self.prepared = False
  269. def serve(self):
  270. """Serve forever."""
  271. self.prepare()
  272. while True:
  273. self.handle()