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