socketserver.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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. # XXX Warning!
  99. # There is a test suite for this module, but it cannot be run by the
  100. # standard regression test.
  101. # To run it manually, run Lib/test/test_socketserver.py.
  102. from __future__ import (absolute_import, print_function)
  103. __version__ = "0.4"
  104. import socket
  105. import select
  106. import sys
  107. import os
  108. import errno
  109. try:
  110. import threading
  111. except ImportError:
  112. import dummy_threading as threading
  113. __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
  114. "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
  115. "StreamRequestHandler","DatagramRequestHandler",
  116. "ThreadingMixIn", "ForkingMixIn"]
  117. if hasattr(socket, "AF_UNIX"):
  118. __all__.extend(["UnixStreamServer","UnixDatagramServer",
  119. "ThreadingUnixStreamServer",
  120. "ThreadingUnixDatagramServer"])
  121. def _eintr_retry(func, *args):
  122. """restart a system call interrupted by EINTR"""
  123. while True:
  124. try:
  125. return func(*args)
  126. except OSError as e:
  127. if e.errno != errno.EINTR:
  128. raise
  129. class BaseServer(object):
  130. """Base class for server classes.
  131. Methods for the caller:
  132. - __init__(server_address, RequestHandlerClass)
  133. - serve_forever(poll_interval=0.5)
  134. - shutdown()
  135. - handle_request() # if you do not use serve_forever()
  136. - fileno() -> int # for select()
  137. Methods that may be overridden:
  138. - server_bind()
  139. - server_activate()
  140. - get_request() -> request, client_address
  141. - handle_timeout()
  142. - verify_request(request, client_address)
  143. - server_close()
  144. - process_request(request, client_address)
  145. - shutdown_request(request)
  146. - close_request(request)
  147. - service_actions()
  148. - handle_error()
  149. Methods for derived classes:
  150. - finish_request(request, client_address)
  151. Class variables that may be overridden by derived classes or
  152. instances:
  153. - timeout
  154. - address_family
  155. - socket_type
  156. - allow_reuse_address
  157. Instance variables:
  158. - RequestHandlerClass
  159. - socket
  160. """
  161. timeout = None
  162. def __init__(self, server_address, RequestHandlerClass):
  163. """Constructor. May be extended, do not override."""
  164. self.server_address = server_address
  165. self.RequestHandlerClass = RequestHandlerClass
  166. self.__is_shut_down = threading.Event()
  167. self.__shutdown_request = False
  168. def server_activate(self):
  169. """Called by constructor to activate the server.
  170. May be overridden.
  171. """
  172. pass
  173. def serve_forever(self, poll_interval=0.5):
  174. """Handle one request at a time until shutdown.
  175. Polls for shutdown every poll_interval seconds. Ignores
  176. self.timeout. If you need to do periodic tasks, do them in
  177. another thread.
  178. """
  179. self.__is_shut_down.clear()
  180. try:
  181. while not self.__shutdown_request:
  182. # XXX: Consider using another file descriptor or
  183. # connecting to the socket to wake this up instead of
  184. # polling. Polling reduces our responsiveness to a
  185. # shutdown request and wastes cpu at all other times.
  186. r, w, e = _eintr_retry(select.select, [self], [], [],
  187. poll_interval)
  188. if self in r:
  189. self._handle_request_noblock()
  190. self.service_actions()
  191. finally:
  192. self.__shutdown_request = False
  193. self.__is_shut_down.set()
  194. def shutdown(self):
  195. """Stops the serve_forever loop.
  196. Blocks until the loop has finished. This must be called while
  197. serve_forever() is running in another thread, or it will
  198. deadlock.
  199. """
  200. self.__shutdown_request = True
  201. self.__is_shut_down.wait()
  202. def service_actions(self):
  203. """Called by the serve_forever() loop.
  204. May be overridden by a subclass / Mixin to implement any code that
  205. needs to be run during the loop.
  206. """
  207. pass
  208. # The distinction between handling, getting, processing and
  209. # finishing a request is fairly arbitrary. Remember:
  210. #
  211. # - handle_request() is the top-level call. It calls
  212. # select, get_request(), verify_request() and process_request()
  213. # - get_request() is different for stream or datagram sockets
  214. # - process_request() is the place that may fork a new process
  215. # or create a new thread to finish the request
  216. # - finish_request() instantiates the request handler class;
  217. # this constructor will handle the request all by itself
  218. def handle_request(self):
  219. """Handle one request, possibly blocking.
  220. Respects self.timeout.
  221. """
  222. # Support people who used socket.settimeout() to escape
  223. # handle_request before self.timeout was available.
  224. timeout = self.socket.gettimeout()
  225. if timeout is None:
  226. timeout = self.timeout
  227. elif self.timeout is not None:
  228. timeout = min(timeout, self.timeout)
  229. fd_sets = _eintr_retry(select.select, [self], [], [], timeout)
  230. if not fd_sets[0]:
  231. self.handle_timeout()
  232. return
  233. self._handle_request_noblock()
  234. def _handle_request_noblock(self):
  235. """Handle one request, without blocking.
  236. I assume that select.select has returned that the socket is
  237. readable before this function was called, so there should be
  238. no risk of blocking in get_request().
  239. """
  240. try:
  241. request, client_address = self.get_request()
  242. except socket.error:
  243. return
  244. if self.verify_request(request, client_address):
  245. try:
  246. self.process_request(request, client_address)
  247. except:
  248. self.handle_error(request, client_address)
  249. self.shutdown_request(request)
  250. def handle_timeout(self):
  251. """Called if no new request arrives within self.timeout.
  252. Overridden by ForkingMixIn.
  253. """
  254. pass
  255. def verify_request(self, request, client_address):
  256. """Verify the request. May be overridden.
  257. Return True if we should proceed with this request.
  258. """
  259. return True
  260. def process_request(self, request, client_address):
  261. """Call finish_request.
  262. Overridden by ForkingMixIn and ThreadingMixIn.
  263. """
  264. self.finish_request(request, client_address)
  265. self.shutdown_request(request)
  266. def server_close(self):
  267. """Called to clean-up the server.
  268. May be overridden.
  269. """
  270. pass
  271. def finish_request(self, request, client_address):
  272. """Finish one request by instantiating RequestHandlerClass."""
  273. self.RequestHandlerClass(request, client_address, self)
  274. def shutdown_request(self, request):
  275. """Called to shutdown and close an individual request."""
  276. self.close_request(request)
  277. def close_request(self, request):
  278. """Called to clean up an individual request."""
  279. pass
  280. def handle_error(self, request, client_address):
  281. """Handle an error gracefully. May be overridden.
  282. The default is to print a traceback and continue.
  283. """
  284. print('-'*40)
  285. print('Exception happened during processing of request from', end=' ')
  286. print(client_address)
  287. import traceback
  288. traceback.print_exc() # XXX But this goes to stderr!
  289. print('-'*40)
  290. class TCPServer(BaseServer):
  291. """Base class for various socket-based server classes.
  292. Defaults to synchronous IP stream (i.e., TCP).
  293. Methods for the caller:
  294. - __init__(server_address, RequestHandlerClass, bind_and_activate=True)
  295. - serve_forever(poll_interval=0.5)
  296. - shutdown()
  297. - handle_request() # if you don't use serve_forever()
  298. - fileno() -> int # for select()
  299. Methods that may be overridden:
  300. - server_bind()
  301. - server_activate()
  302. - get_request() -> request, client_address
  303. - handle_timeout()
  304. - verify_request(request, client_address)
  305. - process_request(request, client_address)
  306. - shutdown_request(request)
  307. - close_request(request)
  308. - handle_error()
  309. Methods for derived classes:
  310. - finish_request(request, client_address)
  311. Class variables that may be overridden by derived classes or
  312. instances:
  313. - timeout
  314. - address_family
  315. - socket_type
  316. - request_queue_size (only for stream sockets)
  317. - allow_reuse_address
  318. Instance variables:
  319. - server_address
  320. - RequestHandlerClass
  321. - socket
  322. """
  323. address_family = socket.AF_INET
  324. socket_type = socket.SOCK_STREAM
  325. request_queue_size = 5
  326. allow_reuse_address = False
  327. def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
  328. """Constructor. May be extended, do not override."""
  329. BaseServer.__init__(self, server_address, RequestHandlerClass)
  330. self.socket = socket.socket(self.address_family,
  331. self.socket_type)
  332. if bind_and_activate:
  333. self.server_bind()
  334. self.server_activate()
  335. def server_bind(self):
  336. """Called by constructor to bind the socket.
  337. May be overridden.
  338. """
  339. if self.allow_reuse_address:
  340. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  341. self.socket.bind(self.server_address)
  342. self.server_address = self.socket.getsockname()
  343. def server_activate(self):
  344. """Called by constructor to activate the server.
  345. May be overridden.
  346. """
  347. self.socket.listen(self.request_queue_size)
  348. def server_close(self):
  349. """Called to clean-up the server.
  350. May be overridden.
  351. """
  352. self.socket.close()
  353. def fileno(self):
  354. """Return socket file number.
  355. Interface required by select().
  356. """
  357. return self.socket.fileno()
  358. def get_request(self):
  359. """Get the request and client address from the socket.
  360. May be overridden.
  361. """
  362. return self.socket.accept()
  363. def shutdown_request(self, request):
  364. """Called to shutdown and close an individual request."""
  365. try:
  366. #explicitly shutdown. socket.close() merely releases
  367. #the socket and waits for GC to perform the actual close.
  368. request.shutdown(socket.SHUT_WR)
  369. except socket.error:
  370. pass #some platforms may raise ENOTCONN here
  371. self.close_request(request)
  372. def close_request(self, request):
  373. """Called to clean up an individual request."""
  374. request.close()
  375. class UDPServer(TCPServer):
  376. """UDP server class."""
  377. allow_reuse_address = False
  378. socket_type = socket.SOCK_DGRAM
  379. max_packet_size = 8192
  380. def get_request(self):
  381. data, client_addr = self.socket.recvfrom(self.max_packet_size)
  382. return (data, self.socket), client_addr
  383. def server_activate(self):
  384. # No need to call listen() for UDP.
  385. pass
  386. def shutdown_request(self, request):
  387. # No need to shutdown anything.
  388. self.close_request(request)
  389. def close_request(self, request):
  390. # No need to close anything.
  391. pass
  392. class ForkingMixIn(object):
  393. """Mix-in class to handle each request in a new process."""
  394. timeout = 300
  395. active_children = None
  396. max_children = 40
  397. def collect_children(self):
  398. """Internal routine to wait for children that have exited."""
  399. if self.active_children is None: return
  400. while len(self.active_children) >= self.max_children:
  401. # XXX: This will wait for any child process, not just ones
  402. # spawned by this library. This could confuse other
  403. # libraries that expect to be able to wait for their own
  404. # children.
  405. try:
  406. pid, status = os.waitpid(0, 0)
  407. except os.error:
  408. pid = None
  409. if pid not in self.active_children: continue
  410. self.active_children.remove(pid)
  411. # XXX: This loop runs more system calls than it ought
  412. # to. There should be a way to put the active_children into a
  413. # process group and then use os.waitpid(-pgid) to wait for any
  414. # of that set, but I couldn't find a way to allocate pgids
  415. # that couldn't collide.
  416. for child in self.active_children:
  417. try:
  418. pid, status = os.waitpid(child, os.WNOHANG)
  419. except os.error:
  420. pid = None
  421. if not pid: continue
  422. try:
  423. self.active_children.remove(pid)
  424. except ValueError as e:
  425. raise ValueError('%s. x=%d and list=%r' % (e.message, pid,
  426. self.active_children))
  427. def handle_timeout(self):
  428. """Wait for zombies after self.timeout seconds of inactivity.
  429. May be extended, do not override.
  430. """
  431. self.collect_children()
  432. def service_actions(self):
  433. """Collect the zombie child processes regularly in the ForkingMixIn.
  434. service_actions is called in the BaseServer's serve_forver loop.
  435. """
  436. self.collect_children()
  437. def process_request(self, request, client_address):
  438. """Fork a new subprocess to process the request."""
  439. pid = os.fork()
  440. if pid:
  441. # Parent process
  442. if self.active_children is None:
  443. self.active_children = []
  444. self.active_children.append(pid)
  445. self.close_request(request)
  446. return
  447. else:
  448. # Child process.
  449. # This must never return, hence os._exit()!
  450. try:
  451. self.finish_request(request, client_address)
  452. self.shutdown_request(request)
  453. os._exit(0)
  454. except:
  455. try:
  456. self.handle_error(request, client_address)
  457. self.shutdown_request(request)
  458. finally:
  459. os._exit(1)
  460. class ThreadingMixIn(object):
  461. """Mix-in class to handle each request in a new thread."""
  462. # Decides how threads will act upon termination of the
  463. # main process
  464. daemon_threads = False
  465. def process_request_thread(self, request, client_address):
  466. """Same as in BaseServer but as a thread.
  467. In addition, exception handling is done here.
  468. """
  469. try:
  470. self.finish_request(request, client_address)
  471. self.shutdown_request(request)
  472. except:
  473. self.handle_error(request, client_address)
  474. self.shutdown_request(request)
  475. def process_request(self, request, client_address):
  476. """Start a new thread to process the request."""
  477. t = threading.Thread(target = self.process_request_thread,
  478. args = (request, client_address))
  479. t.daemon = self.daemon_threads
  480. t.start()
  481. class ForkingUDPServer(ForkingMixIn, UDPServer): pass
  482. class ForkingTCPServer(ForkingMixIn, TCPServer): pass
  483. class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
  484. class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
  485. if hasattr(socket, 'AF_UNIX'):
  486. class UnixStreamServer(TCPServer):
  487. address_family = socket.AF_UNIX
  488. class UnixDatagramServer(UDPServer):
  489. address_family = socket.AF_UNIX
  490. class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
  491. class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
  492. class BaseRequestHandler(object):
  493. """Base class for request handler classes.
  494. This class is instantiated for each request to be handled. The
  495. constructor sets the instance variables request, client_address
  496. and server, and then calls the handle() method. To implement a
  497. specific service, all you need to do is to derive a class which
  498. defines a handle() method.
  499. The handle() method can find the request as self.request, the
  500. client address as self.client_address, and the server (in case it
  501. needs access to per-server information) as self.server. Since a
  502. separate instance is created for each request, the handle() method
  503. can define arbitrary other instance variariables.
  504. """
  505. def __init__(self, request, client_address, server):
  506. self.request = request
  507. self.client_address = client_address
  508. self.server = server
  509. self.setup()
  510. try:
  511. self.handle()
  512. finally:
  513. self.finish()
  514. def setup(self):
  515. pass
  516. def handle(self):
  517. pass
  518. def finish(self):
  519. pass
  520. # The following two classes make it possible to use the same service
  521. # class for stream or datagram servers.
  522. # Each class sets up these instance variables:
  523. # - rfile: a file object from which receives the request is read
  524. # - wfile: a file object to which the reply is written
  525. # When the handle() method returns, wfile is flushed properly
  526. class StreamRequestHandler(BaseRequestHandler):
  527. """Define self.rfile and self.wfile for stream sockets."""
  528. # Default buffer sizes for rfile, wfile.
  529. # We default rfile to buffered because otherwise it could be
  530. # really slow for large data (a getc() call per byte); we make
  531. # wfile unbuffered because (a) often after a write() we want to
  532. # read and we need to flush the line; (b) big writes to unbuffered
  533. # files are typically optimized by stdio even when big reads
  534. # aren't.
  535. rbufsize = -1
  536. wbufsize = 0
  537. # A timeout to apply to the request socket, if not None.
  538. timeout = None
  539. # Disable nagle algorithm for this socket, if True.
  540. # Use only when wbufsize != 0, to avoid small packets.
  541. disable_nagle_algorithm = False
  542. def setup(self):
  543. self.connection = self.request
  544. if self.timeout is not None:
  545. self.connection.settimeout(self.timeout)
  546. if self.disable_nagle_algorithm:
  547. self.connection.setsockopt(socket.IPPROTO_TCP,
  548. socket.TCP_NODELAY, True)
  549. self.rfile = self.connection.makefile('rb', self.rbufsize)
  550. self.wfile = self.connection.makefile('wb', self.wbufsize)
  551. def finish(self):
  552. if not self.wfile.closed:
  553. try:
  554. self.wfile.flush()
  555. except socket.error:
  556. # An final socket error may have occurred here, such as
  557. # the local error ECONNABORTED.
  558. pass
  559. self.wfile.close()
  560. self.rfile.close()
  561. class DatagramRequestHandler(BaseRequestHandler):
  562. # XXX Regrettably, I cannot get this working on Linux;
  563. # s.recvfrom() doesn't return a meaningful client address.
  564. """Define self.rfile and self.wfile for datagram sockets."""
  565. def setup(self):
  566. from io import BytesIO
  567. self.packet, self.socket = self.request
  568. self.rfile = BytesIO(self.packet)
  569. self.wfile = BytesIO()
  570. def finish(self):
  571. self.socket.sendto(self.wfile.getvalue(), self.client_address)