SocketServer.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. """Generic socket server classes.
  2. This module tries to capture the various aspects of defining a server:
  3. For socket-based servers:
  4. - address family:
  5. - AF_INET{,6}: IP (Internet Protocol) sockets (default)
  6. - AF_UNIX: Unix domain sockets
  7. - others, e.g. AF_DECNET are conceivable (see <socket.h>
  8. - socket type:
  9. - SOCK_STREAM (reliable stream, e.g. TCP)
  10. - SOCK_DGRAM (datagrams, e.g. UDP)
  11. For request-based servers (including socket-based):
  12. - client address verification before further looking at the request
  13. (This is actually a hook for any processing that needs to look
  14. at the request before anything else, e.g. logging)
  15. - how to handle multiple requests:
  16. - synchronous (one request is handled at a time)
  17. - forking (each request is handled by a new process)
  18. - threading (each request is handled by a new thread)
  19. The classes in this module favor the server type that is simplest to
  20. write: a synchronous TCP/IP server. This is bad class design, but
  21. save some typing. (There's also the issue that a deep class hierarchy
  22. slows down method lookups.)
  23. There are five classes in an inheritance diagram, four of which represent
  24. synchronous servers of four types:
  25. +------------+
  26. | BaseServer |
  27. +------------+
  28. |
  29. v
  30. +-----------+ +------------------+
  31. | TCPServer |------->| UnixStreamServer |
  32. +-----------+ +------------------+
  33. |
  34. v
  35. +-----------+ +--------------------+
  36. | UDPServer |------->| UnixDatagramServer |
  37. +-----------+ +--------------------+
  38. Note that UnixDatagramServer derives from UDPServer, not from
  39. UnixStreamServer -- the only difference between an IP and a Unix
  40. stream server is the address family, which is simply repeated in both
  41. unix server classes.
  42. Forking and threading versions of each type of server can be created
  43. using the ForkingMixIn and ThreadingMixIn mix-in classes. For
  44. instance, a threading UDP server class is created as follows:
  45. class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
  46. The Mix-in class must come first, since it overrides a method defined
  47. in UDPServer! Setting the various member variables also changes
  48. the behavior of the underlying server mechanism.
  49. To implement a service, you must derive a class from
  50. BaseRequestHandler and redefine its handle() method. You can then run
  51. various versions of the service by combining one of the server classes
  52. with your request handler class.
  53. The request handler class must be different for datagram or stream
  54. services. This can be hidden by using the request handler
  55. subclasses StreamRequestHandler or DatagramRequestHandler.
  56. Of course, you still have to use your head!
  57. For instance, it makes no sense to use a forking server if the service
  58. contains state in memory that can be modified by requests (since the
  59. modifications in the child process would never reach the initial state
  60. kept in the parent process and passed to each child). In this case,
  61. you can use a threading server, but you will probably have to use
  62. locks to avoid two requests that come in nearly simultaneous to apply
  63. conflicting changes to the server state.
  64. On the other hand, if you are building e.g. an HTTP server, where all
  65. data is stored externally (e.g. in the file system), a synchronous
  66. class will essentially render the service "deaf" while one request is
  67. being handled -- which may be for a very long time if a client is slow
  68. to read all the data it has requested. Here a threading or forking
  69. server is appropriate.
  70. In some cases, it may be appropriate to process part of a request
  71. synchronously, but to finish processing in a forked child depending on
  72. the request data. This can be implemented by using a synchronous
  73. server and doing an explicit fork in the request handler class
  74. handle() method.
  75. Another approach to handling multiple simultaneous requests in an
  76. environment that supports neither threads nor fork (or where these are
  77. too expensive or inappropriate for the service) is to maintain an
  78. explicit table of partially finished requests and to use select() to
  79. decide which request to work on next (or whether to handle a new
  80. incoming request). This is particularly important for stream services
  81. where each client can potentially be connected for a long time (if
  82. threads or subprocesses cannot be used).
  83. Future work:
  84. - Standard classes for Sun RPC (which uses either UDP or TCP)
  85. - Standard mix-in classes to implement various authentication
  86. and encryption schemes
  87. - Standard framework for select-based multiplexing
  88. XXX Open problems:
  89. - What to do with out-of-band data?
  90. BaseServer:
  91. - split generic "request" functionality out into BaseServer class.
  92. Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org>
  93. example: read entries from a SQL database (requires overriding
  94. get_request() to return a table entry from the database).
  95. entry is processed by a RequestHandlerClass.
  96. """
  97. # Author of the BaseServer patch: Luke Kenneth Casson Leighton
  98. __version__ = "0.4"
  99. import socket
  100. import select
  101. import sys
  102. import os
  103. import errno
  104. try:
  105. import threading
  106. except ImportError:
  107. import dummy_threading as threading
  108. __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
  109. "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
  110. "StreamRequestHandler","DatagramRequestHandler",
  111. "ThreadingMixIn", "ForkingMixIn"]
  112. if hasattr(socket, "AF_UNIX"):
  113. __all__.extend(["UnixStreamServer","UnixDatagramServer",
  114. "ThreadingUnixStreamServer",
  115. "ThreadingUnixDatagramServer"])
  116. def _eintr_retry(func, *args):
  117. """restart a system call interrupted by EINTR"""
  118. while True:
  119. try:
  120. return func(*args)
  121. except (OSError, select.error) as e:
  122. if e.args[0] != errno.EINTR:
  123. raise
  124. class BaseServer:
  125. """Base class for server classes.
  126. Methods for the caller:
  127. - __init__(server_address, RequestHandlerClass)
  128. - serve_forever(poll_interval=0.5)
  129. - shutdown()
  130. - handle_request() # if you do not use serve_forever()
  131. - fileno() -> int # for select()
  132. Methods that may be overridden:
  133. - server_bind()
  134. - server_activate()
  135. - get_request() -> request, client_address
  136. - handle_timeout()
  137. - verify_request(request, client_address)
  138. - server_close()
  139. - process_request(request, client_address)
  140. - shutdown_request(request)
  141. - close_request(request)
  142. - handle_error()
  143. Methods for derived classes:
  144. - finish_request(request, client_address)
  145. Class variables that may be overridden by derived classes or
  146. instances:
  147. - timeout
  148. - address_family
  149. - socket_type
  150. - allow_reuse_address
  151. Instance variables:
  152. - RequestHandlerClass
  153. - socket
  154. """
  155. timeout = None
  156. def __init__(self, server_address, RequestHandlerClass):
  157. """Constructor. May be extended, do not override."""
  158. self.server_address = server_address
  159. self.RequestHandlerClass = RequestHandlerClass
  160. self.__is_shut_down = threading.Event()
  161. self.__shutdown_request = False
  162. def server_activate(self):
  163. """Called by constructor to activate the server.
  164. May be overridden.
  165. """
  166. pass
  167. def serve_forever(self, poll_interval=0.5):
  168. """Handle one request at a time until shutdown.
  169. Polls for shutdown every poll_interval seconds. Ignores
  170. self.timeout. If you need to do periodic tasks, do them in
  171. another thread.
  172. """
  173. self.__is_shut_down.clear()
  174. try:
  175. while not self.__shutdown_request:
  176. # XXX: Consider using another file descriptor or
  177. # connecting to the socket to wake this up instead of
  178. # polling. Polling reduces our responsiveness to a
  179. # shutdown request and wastes cpu at all other times.
  180. r, w, e = _eintr_retry(select.select, [self], [], [],
  181. poll_interval)
  182. if self in r:
  183. self._handle_request_noblock()
  184. finally:
  185. self.__shutdown_request = False
  186. self.__is_shut_down.set()
  187. def shutdown(self):
  188. """Stops the serve_forever loop.
  189. Blocks until the loop has finished. This must be called while
  190. serve_forever() is running in another thread, or it will
  191. deadlock.
  192. """
  193. self.__shutdown_request = True
  194. self.__is_shut_down.wait()
  195. # The distinction between handling, getting, processing and
  196. # finishing a request is fairly arbitrary. Remember:
  197. #
  198. # - handle_request() is the top-level call. It calls
  199. # select, get_request(), verify_request() and process_request()
  200. # - get_request() is different for stream or datagram sockets
  201. # - process_request() is the place that may fork a new process
  202. # or create a new thread to finish the request
  203. # - finish_request() instantiates the request handler class;
  204. # this constructor will handle the request all by itself
  205. def handle_request(self):
  206. """Handle one request, possibly blocking.
  207. Respects self.timeout.
  208. """
  209. # Support people who used socket.settimeout() to escape
  210. # handle_request before self.timeout was available.
  211. timeout = self.socket.gettimeout()
  212. if timeout is None:
  213. timeout = self.timeout
  214. elif self.timeout is not None:
  215. timeout = min(timeout, self.timeout)
  216. fd_sets = _eintr_retry(select.select, [self], [], [], timeout)
  217. if not fd_sets[0]:
  218. self.handle_timeout()
  219. return
  220. self._handle_request_noblock()
  221. def _handle_request_noblock(self):
  222. """Handle one request, without blocking.
  223. I assume that select.select has returned that the socket is
  224. readable before this function was called, so there should be
  225. no risk of blocking in get_request().
  226. """
  227. try:
  228. request, client_address = self.get_request()
  229. except socket.error:
  230. return
  231. if self.verify_request(request, client_address):
  232. try:
  233. self.process_request(request, client_address)
  234. except:
  235. self.handle_error(request, client_address)
  236. self.shutdown_request(request)
  237. else:
  238. self.shutdown_request(request)
  239. def handle_timeout(self):
  240. """Called if no new request arrives within self.timeout.
  241. Overridden by ForkingMixIn.
  242. """
  243. pass
  244. def verify_request(self, request, client_address):
  245. """Verify the request. May be overridden.
  246. Return True if we should proceed with this request.
  247. """
  248. return True
  249. def process_request(self, request, client_address):
  250. """Call finish_request.
  251. Overridden by ForkingMixIn and ThreadingMixIn.
  252. """
  253. self.finish_request(request, client_address)
  254. self.shutdown_request(request)
  255. def server_close(self):
  256. """Called to clean-up the server.
  257. May be overridden.
  258. """
  259. pass
  260. def finish_request(self, request, client_address):
  261. """Finish one request by instantiating RequestHandlerClass."""
  262. self.RequestHandlerClass(request, client_address, self)
  263. def shutdown_request(self, request):
  264. """Called to shutdown and close an individual request."""
  265. self.close_request(request)
  266. def close_request(self, request):
  267. """Called to clean up an individual request."""
  268. pass
  269. def handle_error(self, request, client_address):
  270. """Handle an error gracefully. May be overridden.
  271. The default is to print a traceback and continue.
  272. """
  273. print '-'*40
  274. print 'Exception happened during processing of request from',
  275. print client_address
  276. import traceback
  277. traceback.print_exc() # XXX But this goes to stderr!
  278. print '-'*40
  279. class TCPServer(BaseServer):
  280. """Base class for various socket-based server classes.
  281. Defaults to synchronous IP stream (i.e., TCP).
  282. Methods for the caller:
  283. - __init__(server_address, RequestHandlerClass, bind_and_activate=True)
  284. - serve_forever(poll_interval=0.5)
  285. - shutdown()
  286. - handle_request() # if you don't use serve_forever()
  287. - fileno() -> int # for select()
  288. Methods that may be overridden:
  289. - server_bind()
  290. - server_activate()
  291. - get_request() -> request, client_address
  292. - handle_timeout()
  293. - verify_request(request, client_address)
  294. - process_request(request, client_address)
  295. - shutdown_request(request)
  296. - close_request(request)
  297. - handle_error()
  298. Methods for derived classes:
  299. - finish_request(request, client_address)
  300. Class variables that may be overridden by derived classes or
  301. instances:
  302. - timeout
  303. - address_family
  304. - socket_type
  305. - request_queue_size (only for stream sockets)
  306. - allow_reuse_address
  307. Instance variables:
  308. - server_address
  309. - RequestHandlerClass
  310. - socket
  311. """
  312. address_family = socket.AF_INET
  313. socket_type = socket.SOCK_STREAM
  314. request_queue_size = 5
  315. allow_reuse_address = False
  316. def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
  317. """Constructor. May be extended, do not override."""
  318. BaseServer.__init__(self, server_address, RequestHandlerClass)
  319. self.socket = socket.socket(self.address_family,
  320. self.socket_type)
  321. if bind_and_activate:
  322. try:
  323. self.server_bind()
  324. self.server_activate()
  325. except:
  326. self.server_close()
  327. raise
  328. def server_bind(self):
  329. """Called by constructor to bind the socket.
  330. May be overridden.
  331. """
  332. if self.allow_reuse_address:
  333. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  334. self.socket.bind(self.server_address)
  335. self.server_address = self.socket.getsockname()
  336. def server_activate(self):
  337. """Called by constructor to activate the server.
  338. May be overridden.
  339. """
  340. self.socket.listen(self.request_queue_size)
  341. def server_close(self):
  342. """Called to clean-up the server.
  343. May be overridden.
  344. """
  345. self.socket.close()
  346. def fileno(self):
  347. """Return socket file number.
  348. Interface required by select().
  349. """
  350. return self.socket.fileno()
  351. def get_request(self):
  352. """Get the request and client address from the socket.
  353. May be overridden.
  354. """
  355. return self.socket.accept()
  356. def shutdown_request(self, request):
  357. """Called to shutdown and close an individual request."""
  358. try:
  359. #explicitly shutdown. socket.close() merely releases
  360. #the socket and waits for GC to perform the actual close.
  361. request.shutdown(socket.SHUT_WR)
  362. except socket.error:
  363. pass #some platforms may raise ENOTCONN here
  364. self.close_request(request)
  365. def close_request(self, request):
  366. """Called to clean up an individual request."""
  367. request.close()
  368. class UDPServer(TCPServer):
  369. """UDP server class."""
  370. allow_reuse_address = False
  371. socket_type = socket.SOCK_DGRAM
  372. max_packet_size = 8192
  373. def get_request(self):
  374. data, client_addr = self.socket.recvfrom(self.max_packet_size)
  375. return (data, self.socket), client_addr
  376. def server_activate(self):
  377. # No need to call listen() for UDP.
  378. pass
  379. def shutdown_request(self, request):
  380. # No need to shutdown anything.
  381. self.close_request(request)
  382. def close_request(self, request):
  383. # No need to close anything.
  384. pass
  385. class ForkingMixIn:
  386. """Mix-in class to handle each request in a new process."""
  387. timeout = 300
  388. active_children = None
  389. max_children = 40
  390. def collect_children(self):
  391. """Internal routine to wait for children that have exited."""
  392. if self.active_children is None:
  393. return
  394. # If we're above the max number of children, wait and reap them until
  395. # we go back below threshold. Note that we use waitpid(-1) below to be
  396. # able to collect children in size(<defunct children>) syscalls instead
  397. # of size(<children>): the downside is that this might reap children
  398. # which we didn't spawn, which is why we only resort to this when we're
  399. # above max_children.
  400. while len(self.active_children) >= self.max_children:
  401. try:
  402. pid, _ = os.waitpid(-1, 0)
  403. self.active_children.discard(pid)
  404. except OSError as e:
  405. if e.errno == errno.ECHILD:
  406. # we don't have any children, we're done
  407. self.active_children.clear()
  408. elif e.errno != errno.EINTR:
  409. break
  410. # Now reap all defunct children.
  411. for pid in self.active_children.copy():
  412. try:
  413. pid, _ = os.waitpid(pid, os.WNOHANG)
  414. # if the child hasn't exited yet, pid will be 0 and ignored by
  415. # discard() below
  416. self.active_children.discard(pid)
  417. except OSError as e:
  418. if e.errno == errno.ECHILD:
  419. # someone else reaped it
  420. self.active_children.discard(pid)
  421. def handle_timeout(self):
  422. """Wait for zombies after self.timeout seconds of inactivity.
  423. May be extended, do not override.
  424. """
  425. self.collect_children()
  426. def process_request(self, request, client_address):
  427. """Fork a new subprocess to process the request."""
  428. self.collect_children()
  429. pid = os.fork()
  430. if pid:
  431. # Parent process
  432. if self.active_children is None:
  433. self.active_children = set()
  434. self.active_children.add(pid)
  435. self.close_request(request) #close handle in parent process
  436. return
  437. else:
  438. # Child process.
  439. # This must never return, hence os._exit()!
  440. try:
  441. self.finish_request(request, client_address)
  442. self.shutdown_request(request)
  443. os._exit(0)
  444. except:
  445. try:
  446. self.handle_error(request, client_address)
  447. self.shutdown_request(request)
  448. finally:
  449. os._exit(1)
  450. class ThreadingMixIn:
  451. """Mix-in class to handle each request in a new thread."""
  452. # Decides how threads will act upon termination of the
  453. # main process
  454. daemon_threads = False
  455. def process_request_thread(self, request, client_address):
  456. """Same as in BaseServer but as a thread.
  457. In addition, exception handling is done here.
  458. """
  459. try:
  460. self.finish_request(request, client_address)
  461. self.shutdown_request(request)
  462. except:
  463. self.handle_error(request, client_address)
  464. self.shutdown_request(request)
  465. def process_request(self, request, client_address):
  466. """Start a new thread to process the request."""
  467. t = threading.Thread(target = self.process_request_thread,
  468. args = (request, client_address))
  469. t.daemon = self.daemon_threads
  470. t.start()
  471. class ForkingUDPServer(ForkingMixIn, UDPServer): pass
  472. class ForkingTCPServer(ForkingMixIn, TCPServer): pass
  473. class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
  474. class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
  475. if hasattr(socket, 'AF_UNIX'):
  476. class UnixStreamServer(TCPServer):
  477. address_family = socket.AF_UNIX
  478. class UnixDatagramServer(UDPServer):
  479. address_family = socket.AF_UNIX
  480. class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
  481. class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
  482. class BaseRequestHandler:
  483. """Base class for request handler classes.
  484. This class is instantiated for each request to be handled. The
  485. constructor sets the instance variables request, client_address
  486. and server, and then calls the handle() method. To implement a
  487. specific service, all you need to do is to derive a class which
  488. defines a handle() method.
  489. The handle() method can find the request as self.request, the
  490. client address as self.client_address, and the server (in case it
  491. needs access to per-server information) as self.server. Since a
  492. separate instance is created for each request, the handle() method
  493. can define other arbitrary instance variables.
  494. """
  495. def __init__(self, request, client_address, server):
  496. self.request = request
  497. self.client_address = client_address
  498. self.server = server
  499. self.setup()
  500. try:
  501. self.handle()
  502. finally:
  503. self.finish()
  504. def setup(self):
  505. pass
  506. def handle(self):
  507. pass
  508. def finish(self):
  509. pass
  510. # The following two classes make it possible to use the same service
  511. # class for stream or datagram servers.
  512. # Each class sets up these instance variables:
  513. # - rfile: a file object from which receives the request is read
  514. # - wfile: a file object to which the reply is written
  515. # When the handle() method returns, wfile is flushed properly
  516. class StreamRequestHandler(BaseRequestHandler):
  517. """Define self.rfile and self.wfile for stream sockets."""
  518. # Default buffer sizes for rfile, wfile.
  519. # We default rfile to buffered because otherwise it could be
  520. # really slow for large data (a getc() call per byte); we make
  521. # wfile unbuffered because (a) often after a write() we want to
  522. # read and we need to flush the line; (b) big writes to unbuffered
  523. # files are typically optimized by stdio even when big reads
  524. # aren't.
  525. rbufsize = -1
  526. wbufsize = 0
  527. # A timeout to apply to the request socket, if not None.
  528. timeout = None
  529. # Disable nagle algorithm for this socket, if True.
  530. # Use only when wbufsize != 0, to avoid small packets.
  531. disable_nagle_algorithm = False
  532. def setup(self):
  533. self.connection = self.request
  534. if self.timeout is not None:
  535. self.connection.settimeout(self.timeout)
  536. if self.disable_nagle_algorithm:
  537. self.connection.setsockopt(socket.IPPROTO_TCP,
  538. socket.TCP_NODELAY, True)
  539. self.rfile = self.connection.makefile('rb', self.rbufsize)
  540. self.wfile = self.connection.makefile('wb', self.wbufsize)
  541. def finish(self):
  542. if not self.wfile.closed:
  543. try:
  544. self.wfile.flush()
  545. except socket.error:
  546. # A final socket error may have occurred here, such as
  547. # the local error ECONNABORTED.
  548. pass
  549. self.wfile.close()
  550. self.rfile.close()
  551. class DatagramRequestHandler(BaseRequestHandler):
  552. """Define self.rfile and self.wfile for datagram sockets."""
  553. def setup(self):
  554. try:
  555. from cStringIO import StringIO
  556. except ImportError:
  557. from StringIO import StringIO
  558. self.packet, self.socket = self.request
  559. self.rfile = StringIO(self.packet)
  560. self.wfile = StringIO()
  561. def finish(self):
  562. self.socket.sendto(self.wfile.getvalue(), self.client_address)