blob: d19146f28feb8ba9690a74c2fdb5082242c159b5 [file] [log] [blame]
Guido van Rossume7e578f1995-08-04 04:00:20 +00001"""Generic socket server classes.
2
3This module tries to capture the various aspects of defining a server:
4
Guido van Rossum90cb9062001-01-19 00:44:41 +00005For socket-based servers:
6
Guido van Rossume7e578f1995-08-04 04:00:20 +00007- address family:
Martin v. Löwisa43c2f82001-07-24 20:34:08 +00008 - AF_INET{,6}: IP (Internet Protocol) sockets (default)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00009 - AF_UNIX: Unix domain sockets
10 - others, e.g. AF_DECNET are conceivable (see <socket.h>
Guido van Rossume7e578f1995-08-04 04:00:20 +000011- socket type:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000012 - SOCK_STREAM (reliable stream, e.g. TCP)
13 - SOCK_DGRAM (datagrams, e.g. UDP)
Guido van Rossum90cb9062001-01-19 00:44:41 +000014
15For request-based servers (including socket-based):
16
Guido van Rossume7e578f1995-08-04 04:00:20 +000017- client address verification before further looking at the request
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000018 (This is actually a hook for any processing that needs to look
19 at the request before anything else, e.g. logging)
Guido van Rossume7e578f1995-08-04 04:00:20 +000020- how to handle multiple requests:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000021 - 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)
Guido van Rossume7e578f1995-08-04 04:00:20 +000024
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
Guido van Rossum90cb9062001-01-19 00:44:41 +000030There are five classes in an inheritance diagram, four of which represent
Guido van Rossume7e578f1995-08-04 04:00:20 +000031synchronous servers of four types:
32
Guido van Rossum90cb9062001-01-19 00:44:41 +000033 +------------+
34 | BaseServer |
35 +------------+
36 |
37 v
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000038 +-----------+ +------------------+
39 | TCPServer |------->| UnixStreamServer |
40 +-----------+ +------------------+
41 |
42 v
43 +-----------+ +--------------------+
44 | UDPServer |------->| UnixDatagramServer |
45 +-----------+ +--------------------+
Guido van Rossume7e578f1995-08-04 04:00:20 +000046
Guido van Rossumdb2b70c1997-07-16 16:21:38 +000047Note that UnixDatagramServer derives from UDPServer, not from
Guido van Rossume7e578f1995-08-04 04:00:20 +000048UnixStreamServer -- the only difference between an IP and a Unix
49stream server is the address family, which is simply repeated in both
Guido van Rossumdb2b70c1997-07-16 16:21:38 +000050unix server classes.
Guido van Rossume7e578f1995-08-04 04:00:20 +000051
52Forking and threading versions of each type of server can be created
Guido van Rossumebbffd42005-04-30 00:20:35 +000053using the ForkingMixIn and ThreadingMixIn mix-in classes. For
Guido van Rossume7e578f1995-08-04 04:00:20 +000054instance, a threading UDP server class is created as follows:
55
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000056 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
Guido van Rossume7e578f1995-08-04 04:00:20 +000057
Guido van Rossumdb2b70c1997-07-16 16:21:38 +000058The Mix-in class must come first, since it overrides a method defined
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +000059in UDPServer! Setting the various member variables also changes
60the behavior of the underlying server mechanism.
Guido van Rossume7e578f1995-08-04 04:00:20 +000061
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
Georg Brandlca5feab2005-07-18 07:38:44 +000068services. This can be hidden by using the request handler
69subclasses StreamRequestHandler or DatagramRequestHandler.
Guido van Rossume7e578f1995-08-04 04:00:20 +000070
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 reqd 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
Guido van Rossum90cb9062001-01-19 00:44:41 +000091server and doing an explicit fork in the request handler class
Guido van Rossume7e578f1995-08-04 04:00:20 +000092handle() 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
Guido van Rossum90cb9062001-01-19 00:44:41 +0000101threads or subprocesses cannot be used).
Guido van Rossume7e578f1995-08-04 04:00:20 +0000102
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
Guido van Rossum90cb9062001-01-19 00:44:41 +0000112BaseServer:
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
Guido van Rossume7e578f1995-08-04 04:00:20 +0000120"""
121
Guido van Rossum10b04182001-01-19 16:45:46 +0000122# Author of the BaseServer patch: Luke Kenneth Casson Leighton
Guido van Rossume7e578f1995-08-04 04:00:20 +0000123
Guido van Rossum7de4d642001-07-10 11:50:09 +0000124# 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"
Guido van Rossume7e578f1995-08-04 04:00:20 +0000130
131
132import socket
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000133import select
Guido van Rossume7e578f1995-08-04 04:00:20 +0000134import sys
135import os
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000136try:
137 import threading
138except ImportError:
139 import dummy_threading as threading
Guido van Rossume7e578f1995-08-04 04:00:20 +0000140
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000141__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
142 "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
Guido van Rossum7de4d642001-07-10 11:50:09 +0000143 "StreamRequestHandler","DatagramRequestHandler",
144 "ThreadingMixIn", "ForkingMixIn"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000145if hasattr(socket, "AF_UNIX"):
146 __all__.extend(["UnixStreamServer","UnixDatagramServer",
147 "ThreadingUnixStreamServer",
148 "ThreadingUnixDatagramServer"])
Guido van Rossume7e578f1995-08-04 04:00:20 +0000149
Guido van Rossum90cb9062001-01-19 00:44:41 +0000150class BaseServer:
151
152 """Base class for server classes.
153
154 Methods for the caller:
155
156 - __init__(server_address, RequestHandlerClass)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000157 - serve_forever(poll_interval=0.5)
158 - shutdown()
Guido van Rossum90cb9062001-01-19 00:44:41 +0000159 - 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
Georg Brandlfceab5a2008-01-19 20:08:23 +0000167 - handle_timeout()
Guido van Rossum90cb9062001-01-19 00:44:41 +0000168 - verify_request(request, client_address)
169 - server_close()
170 - process_request(request, client_address)
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000171 - close_request(request)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000172 - 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
Georg Brandlfceab5a2008-01-19 20:08:23 +0000181 - timeout
Guido van Rossum90cb9062001-01-19 00:44:41 +0000182 - address_family
183 - socket_type
Barry Warsawb97f0b72003-10-09 23:48:52 +0000184 - allow_reuse_address
Guido van Rossum90cb9062001-01-19 00:44:41 +0000185
186 Instance variables:
187
188 - RequestHandlerClass
189 - socket
190
191 """
192
Georg Brandlfceab5a2008-01-19 20:08:23 +0000193 timeout = None
194
Guido van Rossum90cb9062001-01-19 00:44:41 +0000195 def __init__(self, server_address, RequestHandlerClass):
196 """Constructor. May be extended, do not override."""
197 self.server_address = server_address
198 self.RequestHandlerClass = RequestHandlerClass
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000199 self.__is_shut_down = threading.Event()
200 self.__serving = False
Guido van Rossum90cb9062001-01-19 00:44:41 +0000201
202 def server_activate(self):
203 """Called by constructor to activate the server.
204
205 May be overridden.
206
207 """
208 pass
209
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000210 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.__serving = True
218 self.__is_shut_down.clear()
219 while self.__serving:
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 r:
226 self._handle_request_noblock()
227 self.__is_shut_down.set()
228
229 def shutdown(self):
230 """Stops the serve_forever loop.
231
232 Blocks until the loop has finished. This must be called while
233 serve_forever() is running in another thread, or it will
234 deadlock.
235 """
236 self.__serving = False
237 self.__is_shut_down.wait()
Guido van Rossum90cb9062001-01-19 00:44:41 +0000238
239 # The distinction between handling, getting, processing and
240 # finishing a request is fairly arbitrary. Remember:
241 #
242 # - handle_request() is the top-level call. It calls
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000243 # select, get_request(), verify_request() and process_request()
244 # - get_request() is different for stream or datagram sockets
Guido van Rossum90cb9062001-01-19 00:44:41 +0000245 # - process_request() is the place that may fork a new process
246 # or create a new thread to finish the request
247 # - finish_request() instantiates the request handler class;
248 # this constructor will handle the request all by itself
249
250 def handle_request(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000251 """Handle one request, possibly blocking.
252
253 Respects self.timeout.
254 """
255 # Support people who used socket.settimeout() to escape
256 # handle_request before self.timeout was available.
257 timeout = self.socket.gettimeout()
258 if timeout is None:
259 timeout = self.timeout
260 elif self.timeout is not None:
261 timeout = min(timeout, self.timeout)
262 fd_sets = select.select([self], [], [], timeout)
263 if not fd_sets[0]:
264 self.handle_timeout()
265 return
266 self._handle_request_noblock()
267
268 def _handle_request_noblock(self):
269 """Handle one request, without blocking.
270
271 I assume that select.select has returned that the socket is
272 readable before this function was called, so there should be
273 no risk of blocking in get_request().
274 """
Guido van Rossum90cb9062001-01-19 00:44:41 +0000275 try:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000276 request, client_address = self.get_request()
Guido van Rossum90cb9062001-01-19 00:44:41 +0000277 except socket.error:
278 return
279 if self.verify_request(request, client_address):
280 try:
281 self.process_request(request, client_address)
282 except:
283 self.handle_error(request, client_address)
Guido van Rossum7de4d642001-07-10 11:50:09 +0000284 self.close_request(request)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000285
Georg Brandlfceab5a2008-01-19 20:08:23 +0000286 def handle_timeout(self):
287 """Called if no new request arrives within self.timeout.
288
289 Overridden by ForkingMixIn.
290 """
291 pass
292
Guido van Rossum90cb9062001-01-19 00:44:41 +0000293 def verify_request(self, request, client_address):
294 """Verify the request. May be overridden.
295
Tim Petersbc0e9102002-04-04 22:55:58 +0000296 Return True if we should proceed with this request.
Guido van Rossum90cb9062001-01-19 00:44:41 +0000297
298 """
Tim Petersbc0e9102002-04-04 22:55:58 +0000299 return True
Guido van Rossum90cb9062001-01-19 00:44:41 +0000300
301 def process_request(self, request, client_address):
302 """Call finish_request.
303
304 Overridden by ForkingMixIn and ThreadingMixIn.
305
306 """
307 self.finish_request(request, client_address)
Guido van Rossum7de4d642001-07-10 11:50:09 +0000308 self.close_request(request)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000309
310 def server_close(self):
311 """Called to clean-up the server.
312
313 May be overridden.
314
315 """
316 pass
317
318 def finish_request(self, request, client_address):
319 """Finish one request by instantiating RequestHandlerClass."""
320 self.RequestHandlerClass(request, client_address, self)
321
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000322 def close_request(self, request):
323 """Called to clean up an individual request."""
324 pass
325
Guido van Rossum90cb9062001-01-19 00:44:41 +0000326 def handle_error(self, request, client_address):
327 """Handle an error gracefully. May be overridden.
328
329 The default is to print a traceback and continue.
330
331 """
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000332 print('-'*40)
333 print('Exception happened during processing of request from', end=' ')
334 print(client_address)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000335 import traceback
336 traceback.print_exc() # XXX But this goes to stderr!
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000337 print('-'*40)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000338
339
340class TCPServer(BaseServer):
Guido van Rossume7e578f1995-08-04 04:00:20 +0000341
342 """Base class for various socket-based server classes.
343
344 Defaults to synchronous IP stream (i.e., TCP).
345
346 Methods for the caller:
347
Guido van Rossumd8faa362007-04-27 19:54:29 +0000348 - __init__(server_address, RequestHandlerClass, bind_and_activate=True)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000349 - serve_forever(poll_interval=0.5)
350 - shutdown()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000351 - handle_request() # if you don't use serve_forever()
352 - fileno() -> int # for select()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000353
354 Methods that may be overridden:
355
356 - server_bind()
357 - server_activate()
358 - get_request() -> request, client_address
Georg Brandlfceab5a2008-01-19 20:08:23 +0000359 - handle_timeout()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000360 - verify_request(request, client_address)
361 - process_request(request, client_address)
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000362 - close_request(request)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000363 - handle_error()
364
365 Methods for derived classes:
366
367 - finish_request(request, client_address)
368
369 Class variables that may be overridden by derived classes or
370 instances:
371
Georg Brandlfceab5a2008-01-19 20:08:23 +0000372 - timeout
Guido van Rossume7e578f1995-08-04 04:00:20 +0000373 - address_family
374 - socket_type
375 - request_queue_size (only for stream sockets)
Barry Warsaw3aaad502003-10-09 22:44:05 +0000376 - allow_reuse_address
Guido van Rossume7e578f1995-08-04 04:00:20 +0000377
378 Instance variables:
379
380 - server_address
381 - RequestHandlerClass
382 - socket
383
384 """
385
386 address_family = socket.AF_INET
387
388 socket_type = socket.SOCK_STREAM
389
390 request_queue_size = 5
391
Raymond Hettingerc8f80342002-08-25 16:36:49 +0000392 allow_reuse_address = False
Guido van Rossume3c7a5f2000-05-09 14:53:29 +0000393
Guido van Rossumd8faa362007-04-27 19:54:29 +0000394 def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000395 """Constructor. May be extended, do not override."""
Guido van Rossum90cb9062001-01-19 00:44:41 +0000396 BaseServer.__init__(self, server_address, RequestHandlerClass)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000397 self.socket = socket.socket(self.address_family,
398 self.socket_type)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000399 if bind_and_activate:
400 self.server_bind()
401 self.server_activate()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000402
403 def server_bind(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000404 """Called by constructor to bind the socket.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000405
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000406 May be overridden.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000407
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000408 """
Guido van Rossume3c7a5f2000-05-09 14:53:29 +0000409 if self.allow_reuse_address:
410 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000411 self.socket.bind(self.server_address)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000412 self.server_address = self.socket.getsockname()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000413
414 def server_activate(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000415 """Called by constructor to activate the server.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000416
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000417 May be overridden.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000418
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000419 """
420 self.socket.listen(self.request_queue_size)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000421
Guido van Rossum90cb9062001-01-19 00:44:41 +0000422 def server_close(self):
423 """Called to clean-up the server.
424
425 May be overridden.
426
427 """
428 self.socket.close()
429
Guido van Rossume7e578f1995-08-04 04:00:20 +0000430 def fileno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000431 """Return socket file number.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000432
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000433 Interface required by select().
Guido van Rossume7e578f1995-08-04 04:00:20 +0000434
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000435 """
436 return self.socket.fileno()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000437
Guido van Rossume7e578f1995-08-04 04:00:20 +0000438 def get_request(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000439 """Get the request and client address from the socket.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000440
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000441 May be overridden.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000442
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000443 """
444 return self.socket.accept()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000445
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000446 def close_request(self, request):
447 """Called to clean up an individual request."""
448 request.close()
449
Guido van Rossume7e578f1995-08-04 04:00:20 +0000450
451class UDPServer(TCPServer):
452
453 """UDP server class."""
454
Raymond Hettingerc8f80342002-08-25 16:36:49 +0000455 allow_reuse_address = False
Guido van Rossum90cb9062001-01-19 00:44:41 +0000456
Guido van Rossume7e578f1995-08-04 04:00:20 +0000457 socket_type = socket.SOCK_DGRAM
458
459 max_packet_size = 8192
460
461 def get_request(self):
Guido van Rossum32490821998-06-16 02:27:33 +0000462 data, client_addr = self.socket.recvfrom(self.max_packet_size)
463 return (data, self.socket), client_addr
464
465 def server_activate(self):
466 # No need to call listen() for UDP.
467 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000468
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000469 def close_request(self, request):
470 # No need to close anything.
471 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000472
Guido van Rossume7e578f1995-08-04 04:00:20 +0000473class ForkingMixIn:
474
475 """Mix-in class to handle each request in a new process."""
476
Georg Brandlfceab5a2008-01-19 20:08:23 +0000477 timeout = 300
Guido van Rossume7e578f1995-08-04 04:00:20 +0000478 active_children = None
Guido van Rossum2ab455a1999-07-28 21:39:28 +0000479 max_children = 40
Guido van Rossume7e578f1995-08-04 04:00:20 +0000480
481 def collect_children(self):
Georg Brandlfceab5a2008-01-19 20:08:23 +0000482 """Internal routine to wait for children that have exited."""
Christian Heimes70e7ea22008-02-28 20:02:27 +0000483 if self.active_children is None: return
484 while len(self.active_children) >= self.max_children:
485 # XXX: This will wait for any child process, not just ones
486 # spawned by this library. This could confuse other
487 # libraries that expect to be able to wait for their own
488 # children.
Guido van Rossumbfadac01999-06-17 15:41:33 +0000489 try:
Christian Heimes70e7ea22008-02-28 20:02:27 +0000490 pid, status = os.waitpid(0, options=0)
Guido van Rossumbfadac01999-06-17 15:41:33 +0000491 except os.error:
492 pid = None
Christian Heimes70e7ea22008-02-28 20:02:27 +0000493 if pid not in self.active_children: continue
494 self.active_children.remove(pid)
495
496 # XXX: This loop runs more system calls than it ought
497 # to. There should be a way to put the active_children into a
498 # process group and then use os.waitpid(-pgid) to wait for any
499 # of that set, but I couldn't find a way to allocate pgids
500 # that couldn't collide.
501 for child in self.active_children:
502 try:
503 pid, status = os.waitpid(child, os.WNOHANG)
504 except os.error:
505 pid = None
506 if not pid: continue
Christian Heimesa156e092008-02-16 07:38:31 +0000507 try:
508 self.active_children.remove(pid)
509 except ValueError as e:
510 raise ValueError('%s. x=%d and list=%r' % (e.message, pid,
511 self.active_children))
Guido van Rossume7e578f1995-08-04 04:00:20 +0000512
Georg Brandlfceab5a2008-01-19 20:08:23 +0000513 def handle_timeout(self):
514 """Wait for zombies after self.timeout seconds of inactivity.
515
516 May be extended, do not override.
517 """
518 self.collect_children()
519
Guido van Rossume7e578f1995-08-04 04:00:20 +0000520 def process_request(self, request, client_address):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000521 """Fork a new subprocess to process the request."""
522 self.collect_children()
523 pid = os.fork()
524 if pid:
525 # Parent process
526 if self.active_children is None:
527 self.active_children = []
528 self.active_children.append(pid)
Guido van Rossum7de4d642001-07-10 11:50:09 +0000529 self.close_request(request)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000530 return
531 else:
532 # Child process.
533 # This must never return, hence os._exit()!
534 try:
535 self.finish_request(request, client_address)
536 os._exit(0)
537 except:
538 try:
Guido van Rossum7de4d642001-07-10 11:50:09 +0000539 self.handle_error(request, client_address)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000540 finally:
541 os._exit(1)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000542
543
544class ThreadingMixIn:
Guido van Rossume7e578f1995-08-04 04:00:20 +0000545 """Mix-in class to handle each request in a new thread."""
546
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +0000547 # Decides how threads will act upon termination of the
548 # main process
Fred Drake132e0e82002-11-22 14:22:49 +0000549 daemon_threads = False
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +0000550
Guido van Rossuma5343cc2001-10-18 18:02:07 +0000551 def process_request_thread(self, request, client_address):
Guido van Rossum83c32812001-10-23 21:42:45 +0000552 """Same as in BaseServer but as a thread.
553
554 In addition, exception handling is done here.
555
556 """
557 try:
558 self.finish_request(request, client_address)
559 self.close_request(request)
560 except:
561 self.handle_error(request, client_address)
562 self.close_request(request)
Guido van Rossuma5343cc2001-10-18 18:02:07 +0000563
Guido van Rossume7e578f1995-08-04 04:00:20 +0000564 def process_request(self, request, client_address):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000565 """Start a new thread to process the request."""
Guido van Rossuma5343cc2001-10-18 18:02:07 +0000566 t = threading.Thread(target = self.process_request_thread,
Jeremy Hylton75260271999-10-12 16:20:13 +0000567 args = (request, client_address))
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +0000568 if self.daemon_threads:
Benjamin Peterson8b6dc5c2008-09-20 12:52:07 +0000569 t.daemon = True
Jeremy Hylton75260271999-10-12 16:20:13 +0000570 t.start()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000571
572
573class ForkingUDPServer(ForkingMixIn, UDPServer): pass
574class ForkingTCPServer(ForkingMixIn, TCPServer): pass
575
576class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
577class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
578
Guido van Rossum67a40e81998-11-30 15:07:01 +0000579if hasattr(socket, 'AF_UNIX'):
580
581 class UnixStreamServer(TCPServer):
582 address_family = socket.AF_UNIX
583
584 class UnixDatagramServer(UDPServer):
585 address_family = socket.AF_UNIX
586
587 class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
588
589 class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000590
591class BaseRequestHandler:
592
593 """Base class for request handler classes.
594
595 This class is instantiated for each request to be handled. The
596 constructor sets the instance variables request, client_address
597 and server, and then calls the handle() method. To implement a
598 specific service, all you need to do is to derive a class which
599 defines a handle() method.
600
601 The handle() method can find the request as self.request, the
Guido van Rossumfdb3d1a1998-11-16 19:06:30 +0000602 client address as self.client_address, and the server (in case it
Guido van Rossume7e578f1995-08-04 04:00:20 +0000603 needs access to per-server information) as self.server. Since a
604 separate instance is created for each request, the handle() method
605 can define arbitrary other instance variariables.
606
607 """
608
609 def __init__(self, request, client_address, server):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000610 self.request = request
611 self.client_address = client_address
612 self.server = server
Guido van Rossume7ba4952007-06-06 23:52:48 +0000613 self.setup()
614 self.handle()
615 self.finish()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000616
617 def setup(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000618 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000619
Guido van Rossume7e578f1995-08-04 04:00:20 +0000620 def handle(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000621 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000622
623 def finish(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000624 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000625
626
627# The following two classes make it possible to use the same service
628# class for stream or datagram servers.
629# Each class sets up these instance variables:
630# - rfile: a file object from which receives the request is read
631# - wfile: a file object to which the reply is written
632# When the handle() method returns, wfile is flushed properly
633
634
635class StreamRequestHandler(BaseRequestHandler):
636
637 """Define self.rfile and self.wfile for stream sockets."""
638
Guido van Rossum01fed4d2000-09-01 03:25:14 +0000639 # Default buffer sizes for rfile, wfile.
640 # We default rfile to buffered because otherwise it could be
641 # really slow for large data (a getc() call per byte); we make
642 # wfile unbuffered because (a) often after a write() we want to
643 # read and we need to flush the line; (b) big writes to unbuffered
644 # files are typically optimized by stdio even when big reads
645 # aren't.
646 rbufsize = -1
647 wbufsize = 0
648
Guido van Rossume7e578f1995-08-04 04:00:20 +0000649 def setup(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000650 self.connection = self.request
Guido van Rossum01fed4d2000-09-01 03:25:14 +0000651 self.rfile = self.connection.makefile('rb', self.rbufsize)
652 self.wfile = self.connection.makefile('wb', self.wbufsize)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000653
654 def finish(self):
Anthony Baxter4cedc1e2003-01-02 03:07:48 +0000655 if not self.wfile.closed:
656 self.wfile.flush()
Guido van Rossum1d5102c1998-04-03 16:49:52 +0000657 self.wfile.close()
658 self.rfile.close()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000659
660
661class DatagramRequestHandler(BaseRequestHandler):
662
Guido van Rossum7de4d642001-07-10 11:50:09 +0000663 # XXX Regrettably, I cannot get this working on Linux;
664 # s.recvfrom() doesn't return a meaningful client address.
665
Guido van Rossume7e578f1995-08-04 04:00:20 +0000666 """Define self.rfile and self.wfile for datagram sockets."""
667
668 def setup(self):
Guido van Rossum15863ea2007-08-03 19:03:39 +0000669 from io import BytesIO
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000670 self.packet, self.socket = self.request
Guido van Rossum15863ea2007-08-03 19:03:39 +0000671 self.rfile = BytesIO(self.packet)
672 self.wfile = BytesIO()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000673
674 def finish(self):
Guido van Rossum32490821998-06-16 02:27:33 +0000675 self.socket.sendto(self.wfile.getvalue(), self.client_address)