This commit was manufactured by cvs2svn to create tag 'r22a4-fork'.
[python/dscho.git] / Lib / SocketServer.py
blob6e1f78ae1e183a5c4b117bf88b6c0484039b6d71
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 ForkingServer and ThreadingServer 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!
61 To implement a service, you must derive a class from
62 BaseRequestHandler and redefine its handle() method. You can then run
63 various versions of the service by combining one of the server classes
64 with your request handler class.
66 The request handler class must be different for datagram or stream
67 services. This can be hidden by using the mix-in request handler
68 classes StreamRequestHandler or DatagramRequestHandler.
70 Of course, you still have to use your head!
72 For instance, it makes no sense to use a forking server if the service
73 contains state in memory that can be modified by requests (since the
74 modifications in the child process would never reach the initial state
75 kept in the parent process and passed to each child). In this case,
76 you can use a threading server, but you will probably have to use
77 locks to avoid two requests that come in nearly simultaneous to apply
78 conflicting changes to the server state.
80 On the other hand, if you are building e.g. an HTTP server, where all
81 data is stored externally (e.g. in the file system), a synchronous
82 class will essentially render the service "deaf" while one request is
83 being handled -- which may be for a very long time if a client is slow
84 to reqd all the data it has requested. Here a threading or forking
85 server is appropriate.
87 In some cases, it may be appropriate to process part of a request
88 synchronously, but to finish processing in a forked child depending on
89 the request data. This can be implemented by using a synchronous
90 server and doing an explicit fork in the request handler class
91 handle() method.
93 Another approach to handling multiple simultaneous requests in an
94 environment that supports neither threads nor fork (or where these are
95 too expensive or inappropriate for the service) is to maintain an
96 explicit table of partially finished requests and to use select() to
97 decide which request to work on next (or whether to handle a new
98 incoming request). This is particularly important for stream services
99 where each client can potentially be connected for a long time (if
100 threads or subprocesses cannot be used).
102 Future work:
103 - Standard classes for Sun RPC (which uses either UDP or TCP)
104 - Standard mix-in classes to implement various authentication
105 and encryption schemes
106 - Standard framework for select-based multiplexing
108 XXX Open problems:
109 - What to do with out-of-band data?
111 BaseServer:
112 - split generic "request" functionality out into BaseServer class.
113 Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org>
115 example: read entries from a SQL database (requires overriding
116 get_request() to return a table entry from the database).
117 entry is processed by a RequestHandlerClass.
121 # Author of the BaseServer patch: Luke Kenneth Casson Leighton
123 # XXX Warning!
124 # There is a test suite for this module, but it cannot be run by the
125 # standard regression test.
126 # To run it manually, run Lib/test/test_socketserver.py.
128 __version__ = "0.4"
131 import socket
132 import sys
133 import os
135 __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
136 "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
137 "StreamRequestHandler","DatagramRequestHandler",
138 "ThreadingMixIn", "ForkingMixIn"]
139 if hasattr(socket, "AF_UNIX"):
140 __all__.extend(["UnixStreamServer","UnixDatagramServer",
141 "ThreadingUnixStreamServer",
142 "ThreadingUnixDatagramServer"])
144 class BaseServer:
146 """Base class for server classes.
148 Methods for the caller:
150 - __init__(server_address, RequestHandlerClass)
151 - serve_forever()
152 - handle_request() # if you do not use serve_forever()
153 - fileno() -> int # for select()
155 Methods that may be overridden:
157 - server_bind()
158 - server_activate()
159 - get_request() -> request, client_address
160 - verify_request(request, client_address)
161 - server_close()
162 - process_request(request, client_address)
163 - close_request(request)
164 - handle_error()
166 Methods for derived classes:
168 - finish_request(request, client_address)
170 Class variables that may be overridden by derived classes or
171 instances:
173 - address_family
174 - socket_type
175 - reuse_address
177 Instance variables:
179 - RequestHandlerClass
180 - socket
184 def __init__(self, server_address, RequestHandlerClass):
185 """Constructor. May be extended, do not override."""
186 self.server_address = server_address
187 self.RequestHandlerClass = RequestHandlerClass
189 def server_activate(self):
190 """Called by constructor to activate the server.
192 May be overridden.
195 pass
197 def serve_forever(self):
198 """Handle one request at a time until doomsday."""
199 while 1:
200 self.handle_request()
202 # The distinction between handling, getting, processing and
203 # finishing a request is fairly arbitrary. Remember:
205 # - handle_request() is the top-level call. It calls
206 # get_request(), verify_request() and process_request()
207 # - get_request() is different for stream or datagram sockets
208 # - process_request() is the place that may fork a new process
209 # or create a new thread to finish the request
210 # - finish_request() instantiates the request handler class;
211 # this constructor will handle the request all by itself
213 def handle_request(self):
214 """Handle one request, possibly blocking."""
215 try:
216 request, client_address = self.get_request()
217 except socket.error:
218 return
219 if self.verify_request(request, client_address):
220 try:
221 self.process_request(request, client_address)
222 except:
223 self.handle_error(request, client_address)
224 self.close_request(request)
226 def verify_request(self, request, client_address):
227 """Verify the request. May be overridden.
229 Return true if we should proceed with this request.
232 return 1
234 def process_request(self, request, client_address):
235 """Call finish_request.
237 Overridden by ForkingMixIn and ThreadingMixIn.
240 self.finish_request(request, client_address)
241 self.close_request(request)
243 def server_close(self):
244 """Called to clean-up the server.
246 May be overridden.
249 pass
251 def finish_request(self, request, client_address):
252 """Finish one request by instantiating RequestHandlerClass."""
253 self.RequestHandlerClass(request, client_address, self)
255 def close_request(self, request):
256 """Called to clean up an individual request."""
257 pass
259 def handle_error(self, request, client_address):
260 """Handle an error gracefully. May be overridden.
262 The default is to print a traceback and continue.
265 print '-'*40
266 print 'Exception happened during processing of request from',
267 print client_address
268 import traceback
269 traceback.print_exc() # XXX But this goes to stderr!
270 print '-'*40
273 class TCPServer(BaseServer):
275 """Base class for various socket-based server classes.
277 Defaults to synchronous IP stream (i.e., TCP).
279 Methods for the caller:
281 - __init__(server_address, RequestHandlerClass)
282 - serve_forever()
283 - handle_request() # if you don't use serve_forever()
284 - fileno() -> int # for select()
286 Methods that may be overridden:
288 - server_bind()
289 - server_activate()
290 - get_request() -> request, client_address
291 - verify_request(request, client_address)
292 - process_request(request, client_address)
293 - close_request(request)
294 - handle_error()
296 Methods for derived classes:
298 - finish_request(request, client_address)
300 Class variables that may be overridden by derived classes or
301 instances:
303 - address_family
304 - socket_type
305 - request_queue_size (only for stream sockets)
306 - reuse_address
308 Instance variables:
310 - server_address
311 - RequestHandlerClass
312 - socket
316 address_family = socket.AF_INET
318 socket_type = socket.SOCK_STREAM
320 request_queue_size = 5
322 allow_reuse_address = 0
324 def __init__(self, server_address, RequestHandlerClass):
325 """Constructor. May be extended, do not override."""
326 BaseServer.__init__(self, server_address, RequestHandlerClass)
327 self.socket = socket.socket(self.address_family,
328 self.socket_type)
329 self.server_bind()
330 self.server_activate()
332 def server_bind(self):
333 """Called by constructor to bind the socket.
335 May be overridden.
338 if self.allow_reuse_address:
339 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
340 self.socket.bind(self.server_address)
342 def server_activate(self):
343 """Called by constructor to activate the server.
345 May be overridden.
348 self.socket.listen(self.request_queue_size)
350 def server_close(self):
351 """Called to clean-up the server.
353 May be overridden.
356 self.socket.close()
358 def fileno(self):
359 """Return socket file number.
361 Interface required by select().
364 return self.socket.fileno()
366 def get_request(self):
367 """Get the request and client address from the socket.
369 May be overridden.
372 return self.socket.accept()
374 def close_request(self, request):
375 """Called to clean up an individual request."""
376 request.close()
379 class UDPServer(TCPServer):
381 """UDP server class."""
383 allow_reuse_address = 0
385 socket_type = socket.SOCK_DGRAM
387 max_packet_size = 8192
389 def get_request(self):
390 data, client_addr = self.socket.recvfrom(self.max_packet_size)
391 return (data, self.socket), client_addr
393 def server_activate(self):
394 # No need to call listen() for UDP.
395 pass
397 def close_request(self, request):
398 # No need to close anything.
399 pass
401 class ForkingMixIn:
403 """Mix-in class to handle each request in a new process."""
405 active_children = None
406 max_children = 40
408 def collect_children(self):
409 """Internal routine to wait for died children."""
410 while self.active_children:
411 if len(self.active_children) < self.max_children:
412 options = os.WNOHANG
413 else:
414 # If the maximum number of children are already
415 # running, block while waiting for a child to exit
416 options = 0
417 try:
418 pid, status = os.waitpid(0, options)
419 except os.error:
420 pid = None
421 if not pid: break
422 self.active_children.remove(pid)
424 def process_request(self, request, client_address):
425 """Fork a new subprocess to process the request."""
426 self.collect_children()
427 pid = os.fork()
428 if pid:
429 # Parent process
430 if self.active_children is None:
431 self.active_children = []
432 self.active_children.append(pid)
433 self.close_request(request)
434 return
435 else:
436 # Child process.
437 # This must never return, hence os._exit()!
438 try:
439 self.finish_request(request, client_address)
440 os._exit(0)
441 except:
442 try:
443 self.handle_error(request, client_address)
444 finally:
445 os._exit(1)
448 class ThreadingMixIn:
449 """Mix-in class to handle each request in a new thread."""
451 def process_request(self, request, client_address):
452 """Start a new thread to process the request."""
453 import threading
454 t = threading.Thread(target = self.finish_request,
455 args = (request, client_address))
456 t.start()
459 class ForkingUDPServer(ForkingMixIn, UDPServer): pass
460 class ForkingTCPServer(ForkingMixIn, TCPServer): pass
462 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
463 class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
465 if hasattr(socket, 'AF_UNIX'):
467 class UnixStreamServer(TCPServer):
468 address_family = socket.AF_UNIX
470 class UnixDatagramServer(UDPServer):
471 address_family = socket.AF_UNIX
473 class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
475 class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
477 class BaseRequestHandler:
479 """Base class for request handler classes.
481 This class is instantiated for each request to be handled. The
482 constructor sets the instance variables request, client_address
483 and server, and then calls the handle() method. To implement a
484 specific service, all you need to do is to derive a class which
485 defines a handle() method.
487 The handle() method can find the request as self.request, the
488 client address as self.client_address, and the server (in case it
489 needs access to per-server information) as self.server. Since a
490 separate instance is created for each request, the handle() method
491 can define arbitrary other instance variariables.
495 def __init__(self, request, client_address, server):
496 self.request = request
497 self.client_address = client_address
498 self.server = server
499 try:
500 self.setup()
501 self.handle()
502 self.finish()
503 finally:
504 sys.exc_traceback = None # Help garbage collection
506 def setup(self):
507 pass
509 def __del__(self):
510 pass
512 def handle(self):
513 pass
515 def finish(self):
516 pass
519 # The following two classes make it possible to use the same service
520 # class for stream or datagram servers.
521 # Each class sets up these instance variables:
522 # - rfile: a file object from which receives the request is read
523 # - wfile: a file object to which the reply is written
524 # When the handle() method returns, wfile is flushed properly
527 class StreamRequestHandler(BaseRequestHandler):
529 """Define self.rfile and self.wfile for stream sockets."""
531 # Default buffer sizes for rfile, wfile.
532 # We default rfile to buffered because otherwise it could be
533 # really slow for large data (a getc() call per byte); we make
534 # wfile unbuffered because (a) often after a write() we want to
535 # read and we need to flush the line; (b) big writes to unbuffered
536 # files are typically optimized by stdio even when big reads
537 # aren't.
538 rbufsize = -1
539 wbufsize = 0
541 def setup(self):
542 self.connection = self.request
543 self.rfile = self.connection.makefile('rb', self.rbufsize)
544 self.wfile = self.connection.makefile('wb', self.wbufsize)
546 def finish(self):
547 self.wfile.flush()
548 self.wfile.close()
549 self.rfile.close()
552 class DatagramRequestHandler(BaseRequestHandler):
554 # XXX Regrettably, I cannot get this working on Linux;
555 # s.recvfrom() doesn't return a meaningful client address.
557 """Define self.rfile and self.wfile for datagram sockets."""
559 def setup(self):
560 import StringIO
561 self.packet, self.socket = self.request
562 self.rfile = StringIO.StringIO(self.packet)
563 self.wfile = StringIO.StringIO(self.packet)
565 def finish(self):
566 self.socket.sendto(self.wfile.getvalue(), self.client_address)