Eric Smith was missing fro m the issue 7117 whatsnew attribution.
[python.git] / Lib / SocketServer.py
blobff56d986e60a55b55d34b58d57b6768dedf9ff6d
1 """Generic socket server classes.
3 This module tries to capture the various aspects of defining a server:
5 For socket-based servers:
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)
15 For request-based servers (including socket-based):
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)
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.)
30 There are five classes in an inheritance diagram, four of which represent
31 synchronous servers of four types:
33 +------------+
34 | BaseServer |
35 +------------+
38 +-----------+ +------------------+
39 | TCPServer |------->| UnixStreamServer |
40 +-----------+ +------------------+
43 +-----------+ +--------------------+
44 | UDPServer |------->| UnixDatagramServer |
45 +-----------+ +--------------------+
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.
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:
56 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
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.
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.
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.
71 Of course, you still have to use your head!
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.
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.
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.
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).
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
109 XXX Open problems:
110 - What to do with out-of-band data?
112 BaseServer:
113 - split generic "request" functionality out into BaseServer class.
114 Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org>
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.
122 # Author of the BaseServer patch: Luke Kenneth Casson Leighton
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.
129 __version__ = "0.4"
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
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"])
150 class BaseServer:
152 """Base class for server classes.
154 Methods for the caller:
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()
162 Methods that may be overridden:
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 - shutdown_request(request)
172 - close_request(request)
173 - handle_error()
175 Methods for derived classes:
177 - finish_request(request, client_address)
179 Class variables that may be overridden by derived classes or
180 instances:
182 - timeout
183 - address_family
184 - socket_type
185 - allow_reuse_address
187 Instance variables:
189 - RequestHandlerClass
190 - socket
194 timeout = None
196 def __init__(self, server_address, RequestHandlerClass):
197 """Constructor. May be extended, do not override."""
198 self.server_address = server_address
199 self.RequestHandlerClass = RequestHandlerClass
200 self.__is_shut_down = threading.Event()
201 self.__serving = False
203 def server_activate(self):
204 """Called by constructor to activate the server.
206 May be overridden.
209 pass
211 def serve_forever(self, poll_interval=0.5):
212 """Handle one request at a time until shutdown.
214 Polls for shutdown every poll_interval seconds. Ignores
215 self.timeout. If you need to do periodic tasks, do them in
216 another thread.
218 self.__serving = True
219 self.__is_shut_down.clear()
220 while self.__serving:
221 # XXX: Consider using another file descriptor or
222 # connecting to the socket to wake this up instead of
223 # polling. Polling reduces our responsiveness to a
224 # shutdown request and wastes cpu at all other times.
225 r, w, e = select.select([self], [], [], poll_interval)
226 if r:
227 self._handle_request_noblock()
228 self.__is_shut_down.set()
230 def shutdown(self):
231 """Stops the serve_forever loop.
233 Blocks until the loop has finished. This must be called while
234 serve_forever() is running in another thread, or it will
235 deadlock.
237 self.__serving = False
238 self.__is_shut_down.wait()
240 # The distinction between handling, getting, processing and
241 # finishing a request is fairly arbitrary. Remember:
243 # - handle_request() is the top-level call. It calls
244 # select, get_request(), verify_request() and process_request()
245 # - get_request() is different for stream or datagram sockets
246 # - process_request() is the place that may fork a new process
247 # or create a new thread to finish the request
248 # - finish_request() instantiates the request handler class;
249 # this constructor will handle the request all by itself
251 def handle_request(self):
252 """Handle one request, possibly blocking.
254 Respects self.timeout.
256 # Support people who used socket.settimeout() to escape
257 # handle_request before self.timeout was available.
258 timeout = self.socket.gettimeout()
259 if timeout is None:
260 timeout = self.timeout
261 elif self.timeout is not None:
262 timeout = min(timeout, self.timeout)
263 fd_sets = select.select([self], [], [], timeout)
264 if not fd_sets[0]:
265 self.handle_timeout()
266 return
267 self._handle_request_noblock()
269 def _handle_request_noblock(self):
270 """Handle one request, without blocking.
272 I assume that select.select has returned that the socket is
273 readable before this function was called, so there should be
274 no risk of blocking in get_request().
276 try:
277 request, client_address = self.get_request()
278 except socket.error:
279 return
280 if self.verify_request(request, client_address):
281 try:
282 self.process_request(request, client_address)
283 except:
284 self.handle_error(request, client_address)
285 self.shutdown_request(request)
287 def handle_timeout(self):
288 """Called if no new request arrives within self.timeout.
290 Overridden by ForkingMixIn.
292 pass
294 def verify_request(self, request, client_address):
295 """Verify the request. May be overridden.
297 Return True if we should proceed with this request.
300 return True
302 def process_request(self, request, client_address):
303 """Call finish_request.
305 Overridden by ForkingMixIn and ThreadingMixIn.
308 self.finish_request(request, client_address)
309 self.shutdown_request(request)
311 def server_close(self):
312 """Called to clean-up the server.
314 May be overridden.
317 pass
319 def finish_request(self, request, client_address):
320 """Finish one request by instantiating RequestHandlerClass."""
321 self.RequestHandlerClass(request, client_address, self)
323 def shutdown_request(self, request):
324 """Called to shutdown and close an individual request."""
325 self.close_request(request)
327 def close_request(self, request):
328 """Called to clean up an individual request."""
329 pass
331 def handle_error(self, request, client_address):
332 """Handle an error gracefully. May be overridden.
334 The default is to print a traceback and continue.
337 print '-'*40
338 print 'Exception happened during processing of request from',
339 print client_address
340 import traceback
341 traceback.print_exc() # XXX But this goes to stderr!
342 print '-'*40
345 class TCPServer(BaseServer):
347 """Base class for various socket-based server classes.
349 Defaults to synchronous IP stream (i.e., TCP).
351 Methods for the caller:
353 - __init__(server_address, RequestHandlerClass, bind_and_activate=True)
354 - serve_forever(poll_interval=0.5)
355 - shutdown()
356 - handle_request() # if you don't use serve_forever()
357 - fileno() -> int # for select()
359 Methods that may be overridden:
361 - server_bind()
362 - server_activate()
363 - get_request() -> request, client_address
364 - handle_timeout()
365 - verify_request(request, client_address)
366 - process_request(request, client_address)
367 - shutdown_request(request)
368 - close_request(request)
369 - handle_error()
371 Methods for derived classes:
373 - finish_request(request, client_address)
375 Class variables that may be overridden by derived classes or
376 instances:
378 - timeout
379 - address_family
380 - socket_type
381 - request_queue_size (only for stream sockets)
382 - allow_reuse_address
384 Instance variables:
386 - server_address
387 - RequestHandlerClass
388 - socket
392 address_family = socket.AF_INET
394 socket_type = socket.SOCK_STREAM
396 request_queue_size = 5
398 allow_reuse_address = False
400 def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
401 """Constructor. May be extended, do not override."""
402 BaseServer.__init__(self, server_address, RequestHandlerClass)
403 self.socket = socket.socket(self.address_family,
404 self.socket_type)
405 if bind_and_activate:
406 self.server_bind()
407 self.server_activate()
409 def server_bind(self):
410 """Called by constructor to bind the socket.
412 May be overridden.
415 if self.allow_reuse_address:
416 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
417 self.socket.bind(self.server_address)
418 self.server_address = self.socket.getsockname()
420 def server_activate(self):
421 """Called by constructor to activate the server.
423 May be overridden.
426 self.socket.listen(self.request_queue_size)
428 def server_close(self):
429 """Called to clean-up the server.
431 May be overridden.
434 self.socket.close()
436 def fileno(self):
437 """Return socket file number.
439 Interface required by select().
442 return self.socket.fileno()
444 def get_request(self):
445 """Get the request and client address from the socket.
447 May be overridden.
450 return self.socket.accept()
452 def shutdown_request(self, request):
453 """Called to shutdown and close an individual request."""
454 try:
455 #explicitly shutdown. socket.close() merely releases
456 #the socket and waits for GC to perform the actual close.
457 request.shutdown(socket.SHUT_WR)
458 except socket.error:
459 pass #some platforms may raise ENOTCONN here
460 self.close_request(request)
462 def close_request(self, request):
463 """Called to clean up an individual request."""
464 request.close()
467 class UDPServer(TCPServer):
469 """UDP server class."""
471 allow_reuse_address = False
473 socket_type = socket.SOCK_DGRAM
475 max_packet_size = 8192
477 def get_request(self):
478 data, client_addr = self.socket.recvfrom(self.max_packet_size)
479 return (data, self.socket), client_addr
481 def server_activate(self):
482 # No need to call listen() for UDP.
483 pass
485 def shutdown_request(self, request):
486 # No need to shutdown anything.
487 self.close_request(request)
489 def close_request(self, request):
490 # No need to close anything.
491 pass
493 class ForkingMixIn:
495 """Mix-in class to handle each request in a new process."""
497 timeout = 300
498 active_children = None
499 max_children = 40
501 def collect_children(self):
502 """Internal routine to wait for children that have exited."""
503 if self.active_children is None: return
504 while len(self.active_children) >= self.max_children:
505 # XXX: This will wait for any child process, not just ones
506 # spawned by this library. This could confuse other
507 # libraries that expect to be able to wait for their own
508 # children.
509 try:
510 pid, status = os.waitpid(0, 0)
511 except os.error:
512 pid = None
513 if pid not in self.active_children: continue
514 self.active_children.remove(pid)
516 # XXX: This loop runs more system calls than it ought
517 # to. There should be a way to put the active_children into a
518 # process group and then use os.waitpid(-pgid) to wait for any
519 # of that set, but I couldn't find a way to allocate pgids
520 # that couldn't collide.
521 for child in self.active_children:
522 try:
523 pid, status = os.waitpid(child, os.WNOHANG)
524 except os.error:
525 pid = None
526 if not pid: continue
527 try:
528 self.active_children.remove(pid)
529 except ValueError, e:
530 raise ValueError('%s. x=%d and list=%r' % (e.message, pid,
531 self.active_children))
533 def handle_timeout(self):
534 """Wait for zombies after self.timeout seconds of inactivity.
536 May be extended, do not override.
538 self.collect_children()
540 def process_request(self, request, client_address):
541 """Fork a new subprocess to process the request."""
542 self.collect_children()
543 pid = os.fork()
544 if pid:
545 # Parent process
546 if self.active_children is None:
547 self.active_children = []
548 self.active_children.append(pid)
549 self.close_request(request) #close handle in parent process
550 return
551 else:
552 # Child process.
553 # This must never return, hence os._exit()!
554 try:
555 self.finish_request(request, client_address)
556 self.shutdown_request(request)
557 os._exit(0)
558 except:
559 try:
560 self.handle_error(request, client_address)
561 self.shutdown_request(request)
562 finally:
563 os._exit(1)
566 class ThreadingMixIn:
567 """Mix-in class to handle each request in a new thread."""
569 # Decides how threads will act upon termination of the
570 # main process
571 daemon_threads = False
573 def process_request_thread(self, request, client_address):
574 """Same as in BaseServer but as a thread.
576 In addition, exception handling is done here.
579 try:
580 self.finish_request(request, client_address)
581 self.shutdown_request(request)
582 except:
583 self.handle_error(request, client_address)
584 self.shutdown_request(request)
586 def process_request(self, request, client_address):
587 """Start a new thread to process the request."""
588 t = threading.Thread(target = self.process_request_thread,
589 args = (request, client_address))
590 if self.daemon_threads:
591 t.setDaemon (1)
592 t.start()
595 class ForkingUDPServer(ForkingMixIn, UDPServer): pass
596 class ForkingTCPServer(ForkingMixIn, TCPServer): pass
598 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
599 class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
601 if hasattr(socket, 'AF_UNIX'):
603 class UnixStreamServer(TCPServer):
604 address_family = socket.AF_UNIX
606 class UnixDatagramServer(UDPServer):
607 address_family = socket.AF_UNIX
609 class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
611 class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
613 class BaseRequestHandler:
615 """Base class for request handler classes.
617 This class is instantiated for each request to be handled. The
618 constructor sets the instance variables request, client_address
619 and server, and then calls the handle() method. To implement a
620 specific service, all you need to do is to derive a class which
621 defines a handle() method.
623 The handle() method can find the request as self.request, the
624 client address as self.client_address, and the server (in case it
625 needs access to per-server information) as self.server. Since a
626 separate instance is created for each request, the handle() method
627 can define arbitrary other instance variariables.
631 def __init__(self, request, client_address, server):
632 self.request = request
633 self.client_address = client_address
634 self.server = server
635 self.setup()
636 try:
637 self.handle()
638 finally:
639 self.finish()
641 def setup(self):
642 pass
644 def handle(self):
645 pass
647 def finish(self):
648 pass
651 # The following two classes make it possible to use the same service
652 # class for stream or datagram servers.
653 # Each class sets up these instance variables:
654 # - rfile: a file object from which receives the request is read
655 # - wfile: a file object to which the reply is written
656 # When the handle() method returns, wfile is flushed properly
659 class StreamRequestHandler(BaseRequestHandler):
661 """Define self.rfile and self.wfile for stream sockets."""
663 # Default buffer sizes for rfile, wfile.
664 # We default rfile to buffered because otherwise it could be
665 # really slow for large data (a getc() call per byte); we make
666 # wfile unbuffered because (a) often after a write() we want to
667 # read and we need to flush the line; (b) big writes to unbuffered
668 # files are typically optimized by stdio even when big reads
669 # aren't.
670 rbufsize = -1
671 wbufsize = 0
673 # A timeout to apply to the request socket, if not None.
674 timeout = None
676 # Disable nagle algoritm for this socket, if True.
677 # Use only when wbufsize != 0, to avoid small packets.
678 disable_nagle_algorithm = False
680 def setup(self):
681 self.connection = self.request
682 if self.timeout is not None:
683 self.connection.settimeout(self.timeout)
684 if self.disable_nagle_algorithm:
685 self.connection.setsockopt(socket.IPPROTO_TCP,
686 socket.TCP_NODELAY, True)
687 self.rfile = self.connection.makefile('rb', self.rbufsize)
688 self.wfile = self.connection.makefile('wb', self.wbufsize)
690 def finish(self):
691 if not self.wfile.closed:
692 self.wfile.flush()
693 self.wfile.close()
694 self.rfile.close()
697 class DatagramRequestHandler(BaseRequestHandler):
699 # XXX Regrettably, I cannot get this working on Linux;
700 # s.recvfrom() doesn't return a meaningful client address.
702 """Define self.rfile and self.wfile for datagram sockets."""
704 def setup(self):
705 try:
706 from cStringIO import StringIO
707 except ImportError:
708 from StringIO import StringIO
709 self.packet, self.socket = self.request
710 self.rfile = StringIO(self.packet)
711 self.wfile = StringIO()
713 def finish(self):
714 self.socket.sendto(self.wfile.getvalue(), self.client_address)