blob: 5cb89bea196acdf439b7d91033534e05573f0adb [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
Ezio Melottif78869e2011-10-29 10:41:51 +030085to read all the data it has requested. Here a threading or forking
Guido van Rossume7e578f1995-08-04 04:00:20 +000086server 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 os
Antoine Pitroub0a9c662012-04-09 00:47:24 +0200135import errno
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000136try:
137 import threading
Brett Cannoncd171c82013-07-04 17:43:24 -0400138except ImportError:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000139 import dummy_threading as threading
Guido van Rossume7e578f1995-08-04 04:00:20 +0000140
Berker Peksag32653442015-02-03 11:55:09 +0200141__all__ = ["BaseServer", "TCPServer", "UDPServer", "ForkingUDPServer",
142 "ForkingTCPServer", "ThreadingUDPServer", "ThreadingTCPServer",
143 "BaseRequestHandler", "StreamRequestHandler",
144 "DatagramRequestHandler", "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
Antoine Pitroub0a9c662012-04-09 00:47:24 +0200150def _eintr_retry(func, *args):
151 """restart a system call interrupted by EINTR"""
152 while True:
153 try:
154 return func(*args)
155 except OSError as e:
156 if e.errno != errno.EINTR:
157 raise
158
Guido van Rossum90cb9062001-01-19 00:44:41 +0000159class BaseServer:
160
161 """Base class for server classes.
162
163 Methods for the caller:
164
165 - __init__(server_address, RequestHandlerClass)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000166 - serve_forever(poll_interval=0.5)
167 - shutdown()
Guido van Rossum90cb9062001-01-19 00:44:41 +0000168 - handle_request() # if you do not use serve_forever()
169 - fileno() -> int # for select()
170
171 Methods that may be overridden:
172
173 - server_bind()
174 - server_activate()
175 - get_request() -> request, client_address
Georg Brandlfceab5a2008-01-19 20:08:23 +0000176 - handle_timeout()
Guido van Rossum90cb9062001-01-19 00:44:41 +0000177 - verify_request(request, client_address)
178 - server_close()
179 - process_request(request, client_address)
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000180 - shutdown_request(request)
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000181 - close_request(request)
Senthil Kumaran5e826e82011-05-26 00:22:59 +0800182 - service_actions()
Guido van Rossum90cb9062001-01-19 00:44:41 +0000183 - 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
Georg Brandlfceab5a2008-01-19 20:08:23 +0000192 - timeout
Guido van Rossum90cb9062001-01-19 00:44:41 +0000193 - address_family
194 - socket_type
Barry Warsawb97f0b72003-10-09 23:48:52 +0000195 - allow_reuse_address
Guido van Rossum90cb9062001-01-19 00:44:41 +0000196
197 Instance variables:
198
199 - RequestHandlerClass
200 - socket
201
202 """
203
Georg Brandlfceab5a2008-01-19 20:08:23 +0000204 timeout = None
205
Guido van Rossum90cb9062001-01-19 00:44:41 +0000206 def __init__(self, server_address, RequestHandlerClass):
207 """Constructor. May be extended, do not override."""
208 self.server_address = server_address
209 self.RequestHandlerClass = RequestHandlerClass
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000210 self.__is_shut_down = threading.Event()
Antoine Pitrou3bcba8e2010-04-25 22:01:43 +0000211 self.__shutdown_request = False
Guido van Rossum90cb9062001-01-19 00:44:41 +0000212
213 def server_activate(self):
214 """Called by constructor to activate the server.
215
216 May be overridden.
217
218 """
219 pass
220
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000221 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 """
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000228 self.__is_shut_down.clear()
Antoine Pitrou3bcba8e2010-04-25 22:01:43 +0000229 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.
Antoine Pitroub0a9c662012-04-09 00:47:24 +0200235 r, w, e = _eintr_retry(select.select, [self], [], [],
236 poll_interval)
Antoine Pitrou3bcba8e2010-04-25 22:01:43 +0000237 if self in r:
238 self._handle_request_noblock()
Senthil Kumaran5e826e82011-05-26 00:22:59 +0800239
240 self.service_actions()
Antoine Pitrou3bcba8e2010-04-25 22:01:43 +0000241 finally:
242 self.__shutdown_request = False
243 self.__is_shut_down.set()
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000244
245 def shutdown(self):
246 """Stops the serve_forever loop.
247
248 Blocks until the loop has finished. This must be called while
249 serve_forever() is running in another thread, or it will
250 deadlock.
251 """
Antoine Pitrou3bcba8e2010-04-25 22:01:43 +0000252 self.__shutdown_request = True
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000253 self.__is_shut_down.wait()
Guido van Rossum90cb9062001-01-19 00:44:41 +0000254
Senthil Kumaran5e826e82011-05-26 00:22:59 +0800255 def service_actions(self):
256 """Called by the serve_forever() loop.
257
258 May be overridden by a subclass / Mixin to implement any code that
259 needs to be run during the loop.
260 """
261 pass
262
Guido van Rossum90cb9062001-01-19 00:44:41 +0000263 # The distinction between handling, getting, processing and
264 # finishing a request is fairly arbitrary. Remember:
265 #
266 # - handle_request() is the top-level call. It calls
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000267 # select, get_request(), verify_request() and process_request()
268 # - get_request() is different for stream or datagram sockets
Guido van Rossum90cb9062001-01-19 00:44:41 +0000269 # - process_request() is the place that may fork a new process
270 # or create a new thread to finish the request
271 # - finish_request() instantiates the request handler class;
272 # this constructor will handle the request all by itself
273
274 def handle_request(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000275 """Handle one request, possibly blocking.
276
277 Respects self.timeout.
278 """
279 # Support people who used socket.settimeout() to escape
280 # handle_request before self.timeout was available.
281 timeout = self.socket.gettimeout()
282 if timeout is None:
283 timeout = self.timeout
284 elif self.timeout is not None:
285 timeout = min(timeout, self.timeout)
Antoine Pitroub0a9c662012-04-09 00:47:24 +0200286 fd_sets = _eintr_retry(select.select, [self], [], [], timeout)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000287 if not fd_sets[0]:
288 self.handle_timeout()
289 return
290 self._handle_request_noblock()
291
292 def _handle_request_noblock(self):
293 """Handle one request, without blocking.
294
295 I assume that select.select has returned that the socket is
296 readable before this function was called, so there should be
297 no risk of blocking in get_request().
298 """
Guido van Rossum90cb9062001-01-19 00:44:41 +0000299 try:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000300 request, client_address = self.get_request()
Andrew Svetlov0832af62012-12-18 23:10:48 +0200301 except OSError:
Guido van Rossum90cb9062001-01-19 00:44:41 +0000302 return
303 if self.verify_request(request, client_address):
304 try:
305 self.process_request(request, client_address)
306 except:
307 self.handle_error(request, client_address)
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000308 self.shutdown_request(request)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000309
Georg Brandlfceab5a2008-01-19 20:08:23 +0000310 def handle_timeout(self):
311 """Called if no new request arrives within self.timeout.
312
313 Overridden by ForkingMixIn.
314 """
315 pass
316
Guido van Rossum90cb9062001-01-19 00:44:41 +0000317 def verify_request(self, request, client_address):
318 """Verify the request. May be overridden.
319
Tim Petersbc0e9102002-04-04 22:55:58 +0000320 Return True if we should proceed with this request.
Guido van Rossum90cb9062001-01-19 00:44:41 +0000321
322 """
Tim Petersbc0e9102002-04-04 22:55:58 +0000323 return True
Guido van Rossum90cb9062001-01-19 00:44:41 +0000324
325 def process_request(self, request, client_address):
326 """Call finish_request.
327
328 Overridden by ForkingMixIn and ThreadingMixIn.
329
330 """
331 self.finish_request(request, client_address)
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000332 self.shutdown_request(request)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000333
334 def server_close(self):
335 """Called to clean-up the server.
336
337 May be overridden.
338
339 """
340 pass
341
342 def finish_request(self, request, client_address):
343 """Finish one request by instantiating RequestHandlerClass."""
344 self.RequestHandlerClass(request, client_address, self)
345
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000346 def shutdown_request(self, request):
347 """Called to shutdown and close an individual request."""
348 self.close_request(request)
349
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000350 def close_request(self, request):
351 """Called to clean up an individual request."""
352 pass
353
Guido van Rossum90cb9062001-01-19 00:44:41 +0000354 def handle_error(self, request, client_address):
355 """Handle an error gracefully. May be overridden.
356
357 The default is to print a traceback and continue.
358
359 """
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000360 print('-'*40)
361 print('Exception happened during processing of request from', end=' ')
362 print(client_address)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000363 import traceback
364 traceback.print_exc() # XXX But this goes to stderr!
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000365 print('-'*40)
Guido van Rossum90cb9062001-01-19 00:44:41 +0000366
367
368class TCPServer(BaseServer):
Guido van Rossume7e578f1995-08-04 04:00:20 +0000369
370 """Base class for various socket-based server classes.
371
372 Defaults to synchronous IP stream (i.e., TCP).
373
374 Methods for the caller:
375
Guido van Rossumd8faa362007-04-27 19:54:29 +0000376 - __init__(server_address, RequestHandlerClass, bind_and_activate=True)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000377 - serve_forever(poll_interval=0.5)
378 - shutdown()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000379 - handle_request() # if you don't use serve_forever()
380 - fileno() -> int # for select()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000381
382 Methods that may be overridden:
383
384 - server_bind()
385 - server_activate()
386 - get_request() -> request, client_address
Georg Brandlfceab5a2008-01-19 20:08:23 +0000387 - handle_timeout()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000388 - verify_request(request, client_address)
389 - process_request(request, client_address)
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000390 - shutdown_request(request)
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000391 - close_request(request)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000392 - handle_error()
393
394 Methods for derived classes:
395
396 - finish_request(request, client_address)
397
398 Class variables that may be overridden by derived classes or
399 instances:
400
Georg Brandlfceab5a2008-01-19 20:08:23 +0000401 - timeout
Guido van Rossume7e578f1995-08-04 04:00:20 +0000402 - address_family
403 - socket_type
404 - request_queue_size (only for stream sockets)
Barry Warsaw3aaad502003-10-09 22:44:05 +0000405 - allow_reuse_address
Guido van Rossume7e578f1995-08-04 04:00:20 +0000406
407 Instance variables:
408
409 - server_address
410 - RequestHandlerClass
411 - socket
412
413 """
414
415 address_family = socket.AF_INET
416
417 socket_type = socket.SOCK_STREAM
418
419 request_queue_size = 5
420
Raymond Hettingerc8f80342002-08-25 16:36:49 +0000421 allow_reuse_address = False
Guido van Rossume3c7a5f2000-05-09 14:53:29 +0000422
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423 def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000424 """Constructor. May be extended, do not override."""
Guido van Rossum90cb9062001-01-19 00:44:41 +0000425 BaseServer.__init__(self, server_address, RequestHandlerClass)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000426 self.socket = socket.socket(self.address_family,
427 self.socket_type)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000428 if bind_and_activate:
Charles-François Natali0f4f0482014-10-13 19:19:26 +0100429 try:
430 self.server_bind()
431 self.server_activate()
432 except:
433 self.server_close()
434 raise
Guido van Rossume7e578f1995-08-04 04:00:20 +0000435
436 def server_bind(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000437 """Called by constructor to bind the socket.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000438
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000439 May be overridden.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000440
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000441 """
Guido van Rossume3c7a5f2000-05-09 14:53:29 +0000442 if self.allow_reuse_address:
443 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000444 self.socket.bind(self.server_address)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000445 self.server_address = self.socket.getsockname()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000446
447 def server_activate(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000448 """Called by constructor to activate the server.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000449
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000450 May be overridden.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000451
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000452 """
453 self.socket.listen(self.request_queue_size)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000454
Guido van Rossum90cb9062001-01-19 00:44:41 +0000455 def server_close(self):
456 """Called to clean-up the server.
457
458 May be overridden.
459
460 """
461 self.socket.close()
462
Guido van Rossume7e578f1995-08-04 04:00:20 +0000463 def fileno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000464 """Return socket file number.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000465
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000466 Interface required by select().
Guido van Rossume7e578f1995-08-04 04:00:20 +0000467
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000468 """
469 return self.socket.fileno()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000470
Guido van Rossume7e578f1995-08-04 04:00:20 +0000471 def get_request(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000472 """Get the request and client address from the socket.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000473
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000474 May be overridden.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000475
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000476 """
477 return self.socket.accept()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000478
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000479 def shutdown_request(self, request):
480 """Called to shutdown and close an individual request."""
Kristján Valur Jónsson200cfd02009-07-04 15:18:00 +0000481 try:
482 #explicitly shutdown. socket.close() merely releases
483 #the socket and waits for GC to perform the actual close.
484 request.shutdown(socket.SHUT_WR)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200485 except OSError:
Kristján Valur Jónsson200cfd02009-07-04 15:18:00 +0000486 pass #some platforms may raise ENOTCONN here
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000487 self.close_request(request)
488
489 def close_request(self, request):
490 """Called to clean up an individual request."""
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000491 request.close()
492
Guido van Rossume7e578f1995-08-04 04:00:20 +0000493
494class UDPServer(TCPServer):
495
496 """UDP server class."""
497
Raymond Hettingerc8f80342002-08-25 16:36:49 +0000498 allow_reuse_address = False
Guido van Rossum90cb9062001-01-19 00:44:41 +0000499
Guido van Rossume7e578f1995-08-04 04:00:20 +0000500 socket_type = socket.SOCK_DGRAM
501
502 max_packet_size = 8192
503
504 def get_request(self):
Guido van Rossum32490821998-06-16 02:27:33 +0000505 data, client_addr = self.socket.recvfrom(self.max_packet_size)
506 return (data, self.socket), client_addr
507
508 def server_activate(self):
509 # No need to call listen() for UDP.
510 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000511
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000512 def shutdown_request(self, request):
513 # No need to shutdown anything.
514 self.close_request(request)
515
Ka-Ping Yee285a7e52001-04-11 04:02:05 +0000516 def close_request(self, request):
517 # No need to close anything.
518 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000519
Guido van Rossume7e578f1995-08-04 04:00:20 +0000520class ForkingMixIn:
521
522 """Mix-in class to handle each request in a new process."""
523
Georg Brandlfceab5a2008-01-19 20:08:23 +0000524 timeout = 300
Guido van Rossume7e578f1995-08-04 04:00:20 +0000525 active_children = None
Guido van Rossum2ab455a1999-07-28 21:39:28 +0000526 max_children = 40
Guido van Rossume7e578f1995-08-04 04:00:20 +0000527
528 def collect_children(self):
Georg Brandlfceab5a2008-01-19 20:08:23 +0000529 """Internal routine to wait for children that have exited."""
Charles-François Natali504f5c32014-06-20 22:37:35 +0100530 if self.active_children is None:
531 return
Christian Heimes70e7ea22008-02-28 20:02:27 +0000532
Charles-François Natali504f5c32014-06-20 22:37:35 +0100533 # If we're above the max number of children, wait and reap them until
534 # we go back below threshold. Note that we use waitpid(-1) below to be
535 # able to collect children in size(<defunct children>) syscalls instead
536 # of size(<children>): the downside is that this might reap children
537 # which we didn't spawn, which is why we only resort to this when we're
538 # above max_children.
539 while len(self.active_children) >= self.max_children:
Christian Heimes70e7ea22008-02-28 20:02:27 +0000540 try:
Charles-François Natali504f5c32014-06-20 22:37:35 +0100541 pid, _ = os.waitpid(-1, 0)
542 self.active_children.discard(pid)
543 except InterruptedError:
544 pass
545 except ChildProcessError:
546 # we don't have any children, we're done
547 self.active_children.clear()
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200548 except OSError:
Charles-François Natali504f5c32014-06-20 22:37:35 +0100549 break
550
551 # Now reap all defunct children.
552 for pid in self.active_children.copy():
Christian Heimesa156e092008-02-16 07:38:31 +0000553 try:
Charles-François Natali504f5c32014-06-20 22:37:35 +0100554 pid, _ = os.waitpid(pid, os.WNOHANG)
555 # if the child hasn't exited yet, pid will be 0 and ignored by
556 # discard() below
557 self.active_children.discard(pid)
558 except ChildProcessError:
559 # someone else reaped it
560 self.active_children.discard(pid)
561 except OSError:
562 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000563
Georg Brandlfceab5a2008-01-19 20:08:23 +0000564 def handle_timeout(self):
565 """Wait for zombies after self.timeout seconds of inactivity.
566
567 May be extended, do not override.
568 """
569 self.collect_children()
570
Senthil Kumaran5e826e82011-05-26 00:22:59 +0800571 def service_actions(self):
R David Murray258fabe2012-10-01 21:43:46 -0400572 """Collect the zombie child processes regularly in the ForkingMixIn.
Senthil Kumaran5e826e82011-05-26 00:22:59 +0800573
574 service_actions is called in the BaseServer's serve_forver loop.
575 """
576 self.collect_children()
577
Guido van Rossume7e578f1995-08-04 04:00:20 +0000578 def process_request(self, request, client_address):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000579 """Fork a new subprocess to process the request."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000580 pid = os.fork()
581 if pid:
582 # Parent process
583 if self.active_children is None:
Charles-François Natali504f5c32014-06-20 22:37:35 +0100584 self.active_children = set()
585 self.active_children.add(pid)
Guido van Rossum7de4d642001-07-10 11:50:09 +0000586 self.close_request(request)
Senthil Kumaran5e826e82011-05-26 00:22:59 +0800587 return
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000588 else:
589 # Child process.
590 # This must never return, hence os._exit()!
591 try:
592 self.finish_request(request, client_address)
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000593 self.shutdown_request(request)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000594 os._exit(0)
595 except:
596 try:
Guido van Rossum7de4d642001-07-10 11:50:09 +0000597 self.handle_error(request, client_address)
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000598 self.shutdown_request(request)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000599 finally:
600 os._exit(1)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000601
602
603class ThreadingMixIn:
Guido van Rossume7e578f1995-08-04 04:00:20 +0000604 """Mix-in class to handle each request in a new thread."""
605
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +0000606 # Decides how threads will act upon termination of the
607 # main process
Fred Drake132e0e82002-11-22 14:22:49 +0000608 daemon_threads = False
Martin v. Löwisf86e8ef2002-11-22 08:08:44 +0000609
Guido van Rossuma5343cc2001-10-18 18:02:07 +0000610 def process_request_thread(self, request, client_address):
Guido van Rossum83c32812001-10-23 21:42:45 +0000611 """Same as in BaseServer but as a thread.
612
613 In addition, exception handling is done here.
614
615 """
616 try:
617 self.finish_request(request, client_address)
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000618 self.shutdown_request(request)
Guido van Rossum83c32812001-10-23 21:42:45 +0000619 except:
620 self.handle_error(request, client_address)
Kristján Valur Jónssona5b47ce2009-07-07 09:09:10 +0000621 self.shutdown_request(request)
Guido van Rossuma5343cc2001-10-18 18:02:07 +0000622
Guido van Rossume7e578f1995-08-04 04:00:20 +0000623 def process_request(self, request, client_address):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000624 """Start a new thread to process the request."""
Guido van Rossuma5343cc2001-10-18 18:02:07 +0000625 t = threading.Thread(target = self.process_request_thread,
Jeremy Hylton75260271999-10-12 16:20:13 +0000626 args = (request, client_address))
Florent Xicluna12b66b52011-11-04 10:16:28 +0100627 t.daemon = self.daemon_threads
Jeremy Hylton75260271999-10-12 16:20:13 +0000628 t.start()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000629
630
631class ForkingUDPServer(ForkingMixIn, UDPServer): pass
632class ForkingTCPServer(ForkingMixIn, TCPServer): pass
633
634class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
635class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
636
Guido van Rossum67a40e81998-11-30 15:07:01 +0000637if hasattr(socket, 'AF_UNIX'):
638
639 class UnixStreamServer(TCPServer):
640 address_family = socket.AF_UNIX
641
642 class UnixDatagramServer(UDPServer):
643 address_family = socket.AF_UNIX
644
645 class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
646
647 class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000648
649class BaseRequestHandler:
650
651 """Base class for request handler classes.
652
653 This class is instantiated for each request to be handled. The
654 constructor sets the instance variables request, client_address
655 and server, and then calls the handle() method. To implement a
656 specific service, all you need to do is to derive a class which
657 defines a handle() method.
658
659 The handle() method can find the request as self.request, the
Guido van Rossumfdb3d1a1998-11-16 19:06:30 +0000660 client address as self.client_address, and the server (in case it
Guido van Rossume7e578f1995-08-04 04:00:20 +0000661 needs access to per-server information) as self.server. Since a
662 separate instance is created for each request, the handle() method
663 can define arbitrary other instance variariables.
664
665 """
666
667 def __init__(self, request, client_address, server):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000668 self.request = request
669 self.client_address = client_address
670 self.server = server
Guido van Rossume7ba4952007-06-06 23:52:48 +0000671 self.setup()
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000672 try:
673 self.handle()
674 finally:
675 self.finish()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000676
677 def setup(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000678 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000679
Guido van Rossume7e578f1995-08-04 04:00:20 +0000680 def handle(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000681 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000682
683 def finish(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000684 pass
Guido van Rossume7e578f1995-08-04 04:00:20 +0000685
686
687# The following two classes make it possible to use the same service
688# class for stream or datagram servers.
689# Each class sets up these instance variables:
690# - rfile: a file object from which receives the request is read
691# - wfile: a file object to which the reply is written
692# When the handle() method returns, wfile is flushed properly
693
694
695class StreamRequestHandler(BaseRequestHandler):
696
697 """Define self.rfile and self.wfile for stream sockets."""
698
Guido van Rossum01fed4d2000-09-01 03:25:14 +0000699 # Default buffer sizes for rfile, wfile.
700 # We default rfile to buffered because otherwise it could be
701 # really slow for large data (a getc() call per byte); we make
702 # wfile unbuffered because (a) often after a write() we want to
703 # read and we need to flush the line; (b) big writes to unbuffered
704 # files are typically optimized by stdio even when big reads
705 # aren't.
706 rbufsize = -1
707 wbufsize = 0
708
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000709 # A timeout to apply to the request socket, if not None.
710 timeout = None
711
Ezio Melotti4969f702011-03-15 05:59:46 +0200712 # Disable nagle algorithm for this socket, if True.
Kristján Valur Jónsson41a57502009-06-28 21:34:22 +0000713 # Use only when wbufsize != 0, to avoid small packets.
714 disable_nagle_algorithm = False
715
Guido van Rossume7e578f1995-08-04 04:00:20 +0000716 def setup(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000717 self.connection = self.request
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000718 if self.timeout is not None:
719 self.connection.settimeout(self.timeout)
Kristján Valur Jónsson41a57502009-06-28 21:34:22 +0000720 if self.disable_nagle_algorithm:
721 self.connection.setsockopt(socket.IPPROTO_TCP,
722 socket.TCP_NODELAY, True)
Guido van Rossum01fed4d2000-09-01 03:25:14 +0000723 self.rfile = self.connection.makefile('rb', self.rbufsize)
724 self.wfile = self.connection.makefile('wb', self.wbufsize)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000725
726 def finish(self):
Anthony Baxter4cedc1e2003-01-02 03:07:48 +0000727 if not self.wfile.closed:
Kristján Valur Jónsson36852b72012-12-25 22:46:32 +0000728 try:
729 self.wfile.flush()
730 except socket.error:
731 # An final socket error may have occurred here, such as
732 # the local error ECONNABORTED.
733 pass
Guido van Rossum1d5102c1998-04-03 16:49:52 +0000734 self.wfile.close()
735 self.rfile.close()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000736
737
738class DatagramRequestHandler(BaseRequestHandler):
739
Guido van Rossum7de4d642001-07-10 11:50:09 +0000740 # XXX Regrettably, I cannot get this working on Linux;
741 # s.recvfrom() doesn't return a meaningful client address.
742
Guido van Rossume7e578f1995-08-04 04:00:20 +0000743 """Define self.rfile and self.wfile for datagram sockets."""
744
745 def setup(self):
Guido van Rossum15863ea2007-08-03 19:03:39 +0000746 from io import BytesIO
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000747 self.packet, self.socket = self.request
Guido van Rossum15863ea2007-08-03 19:03:39 +0000748 self.rfile = BytesIO(self.packet)
749 self.wfile = BytesIO()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000750
751 def finish(self):
Guido van Rossum32490821998-06-16 02:27:33 +0000752 self.socket.sendto(self.wfile.getvalue(), self.client_address)