Debian Codegraph @

cpython27/Lib/SocketServer.py

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