home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / python2.6 / SocketServer.py < prev    next >
Encoding:
Python Source  |  2010-12-26  |  21.5 KB  |  684 lines

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